Django 6.1.3

4.6 HTTP, routing, and views

View.as_view, MRO, and generic views

Why does View.as_view allocate a brand-new view instance on every request, and how does Python’s MRO assemble ListView and DetailView?

In our newsroom "urls.py", two views are plain functions and two are generic class-based views registered with View.as_view — EditionListView (ListView) and StoryDetailView (DetailView). Passing the class itself (path("stories/<slug:slug>/", StoryDetailView)) is a system check error ("urls.E009" in URLPattern._check_callback, URLPattern._check_callback). You must call View.as_view.

Why View.as_view allocates a fresh instance per request

Remember the singleton hazard from Chapter 3: middleware is instantiated once at worker startup, so attaching per-request data to self inside a middleware causes concurrent threads and coroutines to overwrite each other’s state.

Class-based views deliberately want you to write View.request, View.kwargs, BaseDetailView.object, and "self.edition" across helper methods like get_queryset and get_context_data. If Django instantiated a view class once at "urls.py" import time, every concurrent request would collide on BaseDetailView.object!

Open lines 81–125 of django/views/generic/base.py to see how View.as_view solves that cleanly. Decorated with @classonlymethod (classonlymethod — raising AttributeError if accidentally called on an instance), View.as_view(**initkwargs) does three things at import time:

  1. Validates every keyword argument passed to as_view(...): rejects HTTP method names ("get", "post", etc.) and rejects any key that does not already exist as a class attribute (hasattr(cls, key)), preventing silent typos like passing "tempalte_name" to View.as_view.
  2. Checks View.view_is_async: inspects every implemented HTTP method handler (get, post, etc., ignoring options). All handlers on one CBV must be either all synchronous or all asynchronous — mixing sync get with async def post aborts immediately with ImproperlyConfigured. If async, as_view calls markcoroutinefunction(view) so BaseHandler awaits the closure.
  3. Builds and returns a request closure that stamps "view_class", "view_initkwargs", __doc__, __module__, and View.dispatch’s __dict__, and on every incoming request executes:
def view(request, *args, **kwargs):
    self = cls(**initkwargs)
    self.setup(request, *args, **kwargs)
    if not hasattr(self, "request"):
        raise AttributeError(
            "%s instance has no 'request' attribute. Did you override "
            "setup() and forget to call super()?" % cls.__name__
        )
    return self.dispatch(request, *args, **kwargs)

Inside View.setup, Django binds request, args, and kwargs onto the fresh instance — and automatically aliases head to get if get exists without an explicit head. Then dispatch lowercases HttpRequest.method, checks it against View.http_method_names, and calls getattr(self, method, self.http_method_not_allowed).

Notice how cheap that per-request allocation actually is in our Chapter 4 benchmark (50,000 calls × 5 trials):

Recorded on Django 6.1.3 ch04-bench script
View dispatch overhead (50,000 calls x 5 trials, microseconds per call)
  dispatch_style                             us_per_call   relative
  bare FBV (def view(request))                      6.73       1.00x
  View.as_view() (new instance + dispatch)          8.97        1.33x
  @method_decorator(..., name='dispatch')          13.05        1.94x

Allocating a brand-new View instance, calling setup, and dispatching "GET" adds just 2.24 microseconds over a bare function view (8.97 us vs 6.73 us) — a thousand times smaller than a single database round trip.

Tracing StoryDetailView’s nine-class MRO live

Where generic CBVs actually feel opaque is not View.as_view, but the cooperative multiple-inheritance hierarchy stacked on top of View. DetailView itself has an empty class body — every behaviour comes from mixing SingleObjectTemplateResponseMixin and BaseDetailView (SingleObjectMixin + View), which pull in TemplateResponseMixin and ContextMixin.

Figure 4.3 Both the 9-class MRO and every dispatch step are parsed straight from ch04-routing. Notice that DetailView returns an unrendered TemplateResponse, deferring template rendering and any lazy queryset evaluation back to BaseHandler._get_response.

Watch every single method hop execute live on GET "/stories/bridge-bond-passes/", followed by our two controlled failure tests:

Recorded on Django 6.1.3 ch04-routing script
StoryDetailView MRO, per-request View.as_view dispatch, and class-attribute leak
  StoryDetailView MRO (9 classes): StoryDetailView -> DetailView -> SingleObjectTemplateResponseMixin -> TemplateResponseMixin -> BaseDetailView -> SingleObjectMixin -> ContextMixin -> View -> object
  First request trace (StoryDetailView.as_view()):
    01. View.__init__ (instance #1)
    02. View.setup(kwargs={'slug': 'bridge-bond-passes'})
    03. View.dispatch(method='GET')
    04. BaseDetailView.get
    05. SingleObjectMixin.get_object
    06. StoryDetailView.get_queryset (select_related + prefetch_related)
    07.   resolved Story pk=1 slug='bridge-bond-passes'
    08. SingleObjectMixin.get_context_data -> ContextMixin.get_context_data
    09.   context keys=['object', 'story', 'view']
    10. TemplateResponseMixin.render_to_response
    11.   returned TemplateResponse template_name=['newsroom/story_detail.html'] is_rendered=False
  two calls to same as_view() closure -> distinct_instances=True resp1_is_rendered=False resp2_is_rendered=False
  class-level mutable list leak: req1 -> "count=1 paths=['/a/']"; req2 -> "count=2 paths=['/a/', '/b/']"
  mixed sync+async CBV -> ImproperlyConfigured: MixedCBV HTTP handlers must either be all sync or all async.

Follow that eleven-line call chain across the MRO:

Where class-based views leak

Whether a view is a function or a CBV, two things happen at the very end of every request: either something crashes and Django must render an error report without leaking secrets, or the response streams out and closes its resources cleanly. That final stretch is Debug pages and response lifecycle.