---
django: 6.1.3 (f16e25dcb9fe55734ba4ea2b00ac34405b7df74a)
---

# 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`, `django/urls/resolvers.py:URLPattern._check_callback`). You must call **`View.as_view`** (`django/views/generic/base.py: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` (`django/utils/decorators.py: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` (`django/views/generic/base.py: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:

```python
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/views/generic/base.py: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`** (`django/views/generic/base.py:View.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):

```text recording=ch04-bench
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` (`django/views/generic/detail.py:DetailView`) itself has an empty class body — every behaviour comes from mixing `SingleObjectTemplateResponseMixin` and `BaseDetailView` (`SingleObjectMixin` + `View`), which pull in `TemplateResponseMixin` and `ContextMixin`.

```text figure=cbv-mro
Exact 9-class C3 MRO of StoryDetailView and live per-request dispatch flow on GET /stories/bridge-bond-passes/ (ch04-routing)

Python C3 MRO (left to right, highest priority first):
  1. StoryDetailView -> 2. DetailView -> 3. SingleObjectTemplateResponseMixin -> 4. TemplateResponseMixin
  -> 5. BaseDetailView -> 6. SingleObjectMixin -> 7. ContextMixin -> 8. View -> 9. object

live dispatch on GET /stories/bridge-bond-passes/:
  01. View.__init__ (fresh instance #1 != #2) -> 02. View.setup -> 03. View.dispatch('GET')
  -> 04. BaseDetailView.get -> 05. SingleObjectMixin.get_object -> StoryDetailView.get_queryset (pk=1)
  -> 06. get_context_data (keys=['object', 'story', 'view'])
  -> 07. TemplateResponseMixin.render_to_response (template=['newsroom/story_detail.html'])
  -> 08. returns unrendered TemplateResponse (is_rendered=False)

trap: fresh instance != fresh class attributes — mutating class list seen_paths=[] leaks across requests (count=1 -> count=2).
```

*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:

```text recording=ch04-routing
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`–`03` all belong to `View` (position 8 in the MRO).
- Step `04` lands on `BaseDetailView.get` (`django/views/generic/detail.py:BaseDetailView.get`, position 5), which runs the three-step template method: fetch `self.object = self.get_object()`, build `context = self.get_context_data(object=self.object)`, and return via `TemplateResponseMixin.render_to_response`.
- Step `05` enters `SingleObjectMixin.get_object` (`django/views/generic/detail.py:SingleObjectMixin.get_object`, position 6), which calls *back up* to position 1 (StoryDetailView's `get_queryset`) to grab our newsroom's eager `select_related` + `prefetch_related` queryset, filters by `"slug"`, calls `QuerySet.get`, and translates `ObjectDoesNotExist` into `Http404`.
- Step `08` walks cooperatively through `SingleObjectMixin.get_context_data` (inserting `"object"` and `"story"`, via `context_object_name`) into `ContextMixin.get_context_data` (`django/views/generic/base.py:ContextMixin.get_context_data`, inserting `"view": self` and any `extra_context`).
- Step `10` lands on `TemplateResponseMixin.render_to_response` (`django/views/generic/base.py:TemplateResponseMixin.render_to_response`, position 4), which calls `SingleObjectTemplateResponseMixin.get_template_names` (position 3) and constructs a **`TemplateResponse`** (`django/template/response.py:TemplateResponse`) with `is_rendered = False`. Just as we saw in Chapter 1, the template itself has **not** rendered yet — `BaseHandler._get_response` renders it *after* StoryDetailView's `View.as_view` closure 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_view` constructs a fresh `self = cls(**initkwargs)` per request, so *assigning* `self.extra_context = {...}` creates a safe instance attribute. *Mutating* a class-level list or dictionary in place (`"self.seen_paths.append(...)"` or `self.extra_context["user"] = ...`) 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 `setup()` or `get_context_data()` — or reassign rather than mutating.
- **`queryset = Story.objects.filter(published_at__lte=timezone.now())` freezes at import time.** Defining a dynamic `queryset` as a class attribute evaluates `django.utils.timezone.now` (`django/utils/timezone.py:now`) once when `"views.py"` is imported (`SingleObjectMixin.get_queryset` calls `QuerySet.all` on `SingleObjectMixin.queryset` to clone it, which re-executes the SQL with the *old* frozen timestamp!). Any time-dependent or request-dependent filter belongs inside `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 an `async def post`, its `get` handler must also be `async 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](errors-and-debug.md).
