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

# MiddlewareMixin and short-circuits

How do `process_request`, `process_view`, `process_template_response`, and `process_response` fit into modern callable middleware, and what skips when a layer returns early?

Modern Django middleware is supposed to be a simple callable taking `get_response` and returning a function of `request`. Yet when we inspected all seven built-in middleware classes in `"desk.settings"` in the previous section, every single one of them — `SecurityMiddleware`, `SessionMiddleware`, `CommonMiddleware`, `CsrfViewMiddleware`, `AuthenticationMiddleware`, `MessageMiddleware`, and `XFrameOptionsMiddleware` — inherited from **`MiddlewareMixin`** (`django/utils/deprecation.py:MiddlewareMixin`).

Ten years after Django replaced `"MIDDLEWARE_CLASSES"` with `"MIDDLEWARE"`, the "deprecation" mixin is still the backbone of Django's own default stack. To understand how hooks, short-circuits, and ASGI thread crossings behave, you have to open `MiddlewareMixin` itself.

## Why DEP 0005 changed the rules

> **History.** Before Django 1.10, `"MIDDLEWARE_CLASSES"` ran as flat loops over separate hook methods (`process_request`, `process_view`, `process_response`, `process_exception`). In January 2016, Carl Meyer authored DEP 0005 (`deps:final/0005-improved-middleware.rst`), modelled on Pyramid's Tweens, to fix a broken invariant that had already doomed Django's old `"TransactionMiddleware"`: *"It is possible for a middleware to have its `process_request` method called, but then never see its `process_response` or `process_exception` called for that request... It is also possible for a middleware to never see its `process_request` method called for a given request (because an earlier middleware's `process_request` returned a response), but still have its `process_response` or `process_exception` method called on that response."* Calling middleware factories *"Turtles all the way down!"*, DEP 0005 made the onion literal: every layer wraps the next via `get_response`, so any layer entered on the way in is guaranteed to unwind on the way out, and any layer skipped on the way in stays skipped on the way out.

```text figure=onion-and-hooks
Concentric middleware onion, per-layer convert_exception_to_response walls, hook order, and short-circuit symmetry (ch03-handlers)

nested layers (outer -> inner, each wrapped in convert_exception_to_response):
  OuterMW -> MiddleMW -> InnerMW -> Core (BaseHandler._get_response)

inward request path (top -> bottom):
  Outer.process_request -> Middle.process_request -> Inner.process_request
  -> resolve_request -> Outer.process_view -> Middle.process_view -> Inner.process_view -> view

outward response path (bottom -> top):
  Inner.process_template_response -> Middle.process_template_response -> Outer.process_template_response
  -> TemplateResponse.render
  -> Inner.process_response -> Middle.process_response -> Outer.process_response

short-circuit in Middle.process_request (5 steps vs 14 full pass, 9 view short-circuit):
  Outer.process_request -> Middle.process_request -> SHORT-CIRCUIT 200
  -> Middle.process_response -> Outer.process_response   (Inner, resolve_request, process_view, view all skipped)
```

*Every step count is parsed from `ch03-handlers`. The hatched outer edge of every ring marks the `convert_exception_to_response` boundary installed by `BaseHandler.load_middleware`; the dashed red U-turn shows DEP 0005's short-circuit symmetry when the middle layer's `process_request` returns early.*

## Inside `MiddlewareMixin.__call__`

Open lines 408–464 of `django/utils/deprecation.py`. `MiddlewareMixin` declares `sync_capable = True` and `async_capable = True`. In `MiddlewareMixin.__init__` (`django/utils/deprecation.py:MiddlewareMixin.__init__`), it inspects `iscoroutinefunction(self.get_response)` (`asgiref:asgiref/sync.py:iscoroutinefunction`); if the inner callable is async, it sets `self.async_mode = True` and stamps the instance with `markcoroutinefunction(self)` (`asgiref:asgiref/sync.py:markcoroutinefunction`) so the next outer ring sees it as awaitable.

Then `MiddlewareMixin.__call__` (`django/utils/deprecation.py:MiddlewareMixin.__call__`) bridges the old hook methods into the new callable contract in seven lines:

```python
def __call__(self, request):
    if self.async_mode:
        return self.__acall__(request)
    response = None
    if hasattr(self, "process_request"):
        response = self.process_request(request)
    response = response or self.get_response(request)
    if hasattr(self, "process_response"):
        response = self.process_response(request, response)
    return response
```

Read those three `if`/`or` lines slowly, because every nuance of request-phase short-circuiting sits right there. If `process_request` returns `None` (the common case), `response or self.get_response(request)` calls the next inner ring of the onion. If `process_request` returns an `HttpResponse` — a **short-circuit response** (such as an HTTPS redirect in `SecurityMiddleware`, a cached page in `FetchFromCacheMiddleware`, or a rate-limit `429`) — the `or` operator skips `MiddlewareMixin.get_response` completely. Yet notice the very next line: **`process_response` STILL runs on the middleware that short-circuited**, and then every outer middleware's `process_response` runs as the call stack unwinds.

Now glance five lines lower at `MiddlewareMixin.__acall__` (`django/utils/deprecation.py:MiddlewareMixin.__acall__`): it executes the exact same logic, except it wraps `process_request` and `process_response` individually in `await sync_to_async(..., thread_sensitive=True)`. That innocent-looking compatibility shim is what produces `13` thread-pool crossings on Django's default ASGI stack.

## The core hooks: `process_view` and `process_template_response`

When no `process_request` short-circuits, the request reaches the centre of the onion: `BaseHandler._get_response` (`django/core/handlers/base.py:BaseHandler._get_response`) or `BaseHandler._get_response_async` (`django/core/handlers/base.py:BaseHandler._get_response_async`). Here Django runs three phases that ordinary outer middleware cannot easily perform on its own:

1. **URL resolution and `process_view`:** First, `BaseHandler.resolve_request` (`django/core/handlers/base.py:BaseHandler.resolve_request`) resolves `HttpRequest.path_info` (`django/http/request.py:HttpRequest`) into `(callback, callback_args, callback_kwargs)` and attaches `HttpRequest.resolver_match`. Only now does Django know *which view function* is about to run. It loops top-to-bottom over `BaseHandler._view_middleware`, calling each middleware's **`process_view`** hook with `(request, callback, callback_args, callback_kwargs)`. That is why `CsrfViewMiddleware` implements `process_view` (`django/middleware/csrf.py:CsrfViewMiddleware.process_view`) rather than `process_request`: it has to inspect `getattr(callback, "csrf_exempt", False)` on the resolved view before deciding whether to reject a POST without a CSRF token. If any `process_view` returns a truthy `HttpResponse`, the loop breaks immediately, skipping any remaining `process_view` hooks and the view itself.
2. **View execution (with `"ATOMIC_REQUESTS"`):** If no `process_view` returned a response, Django passes `callback` through `BaseHandler.make_view_atomic` (`django/core/handlers/base.py:BaseHandler.make_view_atomic`), adapts sync/async mode if the view disagrees with the handler, calls the view inside `try/except Exception` (passing view exceptions to `BaseHandler.process_exception_by_middleware`), and validates the return value with `BaseHandler.check_response` (`django/core/handlers/base.py:BaseHandler.check_response`).
3. **Deferred rendering and `process_template_response`:** If the returned response has a callable `"render"` attribute — such as `TemplateResponse` (`django/template/response.py:TemplateResponse`) — Django loops bottom-to-top over `BaseHandler._template_response_middleware`, letting each hook inspect or mutate `context_data` or `template_name` and return a response (checked again by `check_response`). Only *after* every `process_template_response` hook finishes does Django call `SimpleTemplateResponse.render` (`django/template/response.py:SimpleTemplateResponse.render`), turning the lazy template into HTML bytes — inside another `try/except Exception` block so template crashes also reach `process_exception`!

## Comparing all three traces live

Instrument three `MiddlewareMixin` layers (outer, middle, inner) around a view returning a `TemplateResponse`, and record a full pass against short-circuits in `process_request` and `process_view`:

```text recording=ch03-handlers
Onion hook ordering: full pass vs process_request and process_view short-circuits
  Full pass (TemplateResponse view) -> 200 OK (rendered-body):
    01. Outer.process_request
    02. Middle.process_request
    03. Inner.process_request
    04. Outer.process_view
    05. Middle.process_view
    06. Inner.process_view
    07. view.probe_view
    08. Inner.process_template_response
    09. Middle.process_template_response
    10. Outer.process_template_response
    11. TemplateResponse.render
    12. Inner.process_response(status=200)
    13. Middle.process_response(status=200)
    14. Outer.process_response(status=200)
  
  Short-circuit in Middle.process_request -> 200 OK (short-circuited in process_request):
    01. Outer.process_request
    02. Middle.process_request
    03. Middle.process_request -> SHORT-CIRCUIT 200
    04. Middle.process_response(status=200)
    05. Outer.process_response(status=200)
  
  Short-circuit in Middle.process_view -> 200 OK (short-circuited in process_view):
    01. Outer.process_request
    02. Middle.process_request
    03. Inner.process_request
    04. Outer.process_view
    05. Middle.process_view
    06. Middle.process_view -> SHORT-CIRCUIT 200
    07. Inner.process_response(status=200)
    08. Middle.process_response(status=200)
    09. Outer.process_response(status=200)
```

Compare the second and third traces carefully — they highlight a subtle distinction engineers frequently mispredict.

When the middle layer short-circuits in `process_request` (`5` steps), the inner layer was never entered, so Inner's `process_request` and `process_response` are both skipped. When the middle layer short-circuits in `process_view` (`9` steps), all three `process_request` methods have *already* run to reach `BaseHandler._get_response`! So although the inner layer's `process_view` and the view itself are skipped, the short-circuit response returns *out of* `BaseHandler._get_response` into the inner layer's waiting stack frame — meaning **Inner's `process_response` still runs** (`step 07`), followed by Middle's and Outer's `process_response`.

## Where hooks and short-circuits leak

- **Short-circuiting before `SecurityMiddleware` or `XFrameOptionsMiddleware` drops headers.** If a custom rate-limit or maintenance middleware sits *above* `SecurityMiddleware` and returns a short-circuit response, none of the inner security middlewares run on that response — so the `429` or `503` leaves the server without `"X-Frame-Options"`, `"X-Content-Type-Options"`, or HSTS headers.
- **`process_template_response` silently skips views using `django.shortcuts.render`.** Remember Chapter 1: `django.shortcuts.render` renders the template immediately and returns a plain `HttpResponse` with no `SimpleTemplateResponse.render` method. Any middleware relying on `process_template_response` will execute on generic CBVs (like our newsroom's EditionListView and StoryDetailView), and silently do nothing on function views using `django.shortcuts.render`.
- **Forgetting to return a response crashes in `check_response`.** Returning `None` — or forgetting `await` inside an `async def` view so it returns a raw coroutine object — raises a descriptive `ValueError` inside `BaseHandler.check_response`, which immediately hits the exception wall we open next in [Exception walls and error responses](exceptions.md).
