1.The View base class and dispatch()
Every class-based view subclasses View, whose as_view() returns a plain function Django can call like any FBV. dispatch() is what that function actually runs — it looks at request.method and calls the matching method (get(), post(), ...) on the instance.
Key features
- MyView.as_view() returns a function — that function, not the class, is what urls.py actually calls
- dispatch(self, request, *args, **kwargs) looks up self.get/self.post/etc. based on request.method.lower()
- A method not defined on the view (e.g. no post() on a GET-only view) falls through to http_method_not_allowed — a 405
- get(), post(), put(), delete() etc. all receive the same (self, request, *args, **kwargs) signature
- Every generic view (TemplateView, ListView, DetailView...) is ultimately a View subclass — dispatch() is inherited, not reimplemented
What as_view() and dispatch() actually do
- urlpatterns — MyView.as_view()
- leads to dispatch()
- dispatch() — checks request.method
- leads to self.get() / self.post()
- self.get() / self.post()
Command
from django.views import View
from django.http import HttpResponse
class Echo(View):
def get(self, request):
return HttpResponse("GET received")
def post(self, request):
return HttpResponse("POST received")MyView.as_view() returns a function urls.py can call; dispatch() (inherited, not written by hand) routes to get()/post()/etc. based on request.method — a missing method becomes an automatic 405.