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/) is a system check error ("urls.E009" in URLPattern, URLPattern). 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, 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!
Open lines 81–125 of django/ to see how View.as_view solves that cleanly. Decorated with @classonlymethod (classonlymethod — raising AttributeError if accidentally called on an instance), View does three things at import time:
- 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"toView.as_view. - Checks
View: inspects every implemented HTTP method handler (.view_is_async get,post, etc., ignoringoptions). All handlers on one CBV must be either all synchronous or all asynchronous — mixing syncgetwithasync def postaborts immediately withImproperlyConfigured. If async,as_viewcallsmarkcoroutinefunction(view)soBaseHandlerawaits the closure. - Builds and returns a request closure that stamps
"view_class","view_initkwargs",__doc__,__module__, andView.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, checks it against View, and calls getattr(self, method, self.
Notice how cheap that per-request allocation actually is in our Chapter 4 benchmark (50,000 calls × 5 trials):
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 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.
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 "/, followed by our two controlled failure tests:
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:
- Steps
01–03all belong toView(position 8 in the MRO). - Step
04lands onBaseDetailView(.get BaseDetailView, position 5), which runs the three-step template method: fetch.get self, build.object = self .get_object() context = self, and return via.get_context_data(object=self .object) TemplateResponseMixin..render_to_response - Step
05entersSingleObjectMixin(.get_object SingleObjectMixin, position 6), which calls back up to position 1 (StoryDetailView’s.get_object get_queryset) to grab our newsroom’s eagerselect_related+prefetch_relatedqueryset, filters by"slug", callsQuerySet.get, and translatesObjectDoesNotExistintoHttp404. - Step
08walks cooperatively throughSingleObjectMixin(inserting.get_context_data "object"and"story", viacontext_object_name) intoContextMixin(.get_context_data ContextMixin, inserting.get_context_data "view": selfand anyextra_context). - Step
10lands onTemplateResponseMixin(.render_to_response TemplateResponseMixin, position 4), which calls.render_to_response SingleObjectTemplateResponseMixin(position 3) and constructs a.get_template_names TemplateResponsewithis_rendered = False. Just as we saw in Chapter 1, the template itself has not rendered yet —BaseHandlerrenders it after StoryDetailView’s._get_response View.as_viewclosure returns!
Where class-based views leak
- Fresh instance does NOT copy mutable class attributes. Look at the second-to-last line of our recording (
req1 -> "count=1 paths=['/).a/ ']"; req2 -> "count=2 paths=['/ a/ ', '/ b/ ']" View.as_viewconstructs a freshself = cls(**initkwargs)per request, so assigningselfcreates a safe instance attribute. Mutating a class-level list or dictionary in place (.extra_context = {...} "selfor.seen_paths .append(...)" self) mutates the shared object on the class itself, leaking data from User A into User B across requests! Always initialize mutable per-request state inside.extra_context["user"] = ... setup()orget_context_data()— or reassign rather than mutating. queryset = Storyfreezes at import time. Defining a dynamic.objects .filter(published_at__lte=timezone .now()) querysetas a class attribute evaluatesdjangoonce when.utils .timezone .now "views.py"is imported (SingleObjectMixincalls.get_queryset QuerySet.allonSingleObjectMixinto clone it, which re-executes the SQL with the old frozen timestamp!). Any time-dependent or request-dependent filter belongs inside.queryset get_queryset(self).- Mixing sync and async methods on one CBV crashes
as_view(). As line 75 of our recording proved, if a CBV needs anasync def post, itsgethandler must also beasync def get(or split into separate views).
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.