Performance: View base class
This affects server response time and how quickly the page content is generated and sent to the browser.
Jump into concepts and practice - no test required
from django.views.generic import TemplateView class MyView(TemplateView): template_name = 'my_template.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['data'] = cached_or_optimized_query() return context
from django.views import View from django.http import HttpResponse class MyView(View): def get(self, request): data = complex_database_query() processed = heavy_processing(data) return HttpResponse(processed)
| Pattern | Server Processing | Response Time | Network Payload | Verdict |
|---|---|---|---|---|
| Heavy logic in base View | High CPU and DB load | Slow (200-500ms) | Normal | [X] Bad |
| Generic TemplateView with caching | Low CPU and DB load | Fast (50-100ms) | Normal | [OK] Good |
View base class?get() and post() inside one class.as_view() on the View class to create a callable view function for URLs.get() method directly, which is not how URLs connect. path('home/', HomeView.render()) uses a non-existent render() method.from django.views import View
from django.http import HttpResponse
class HelloView(View):
def get(self, request):
return HttpResponse('Hello, world!')request and returns a valid HttpResponse, so no errors or empty responses occur.from django.views import View
from django.http import HttpResponse
class MyView(View):
def get(self):
return HttpResponse('Hi')self and request parameters. Here, request is missing.from django.views import View
from django.http import HttpResponse
class ContactView(View):
def get(self, request):
return HttpResponse('Show form')
def post(self, request):
# process form data
return HttpResponse('Form submitted')get() and post() methods inside the View subclass, each accepting self and request.