Django 6.1.3

4.5 HTTP, routing, and views

Function views and decorator wrappers

What does a view decorator actually wrap, and why can stacking decorators in the wrong order or on async views break silently?

A Django view decorator is a higher-order function that takes a view callable (request, *args, **kwargs) -> HttpResponse and returns a replacement wrapper callable that runs before, around, or instead of the inner view. Because Python evaluates stacked @ decorators bottom-up at import time and executes them top-down at request time, every decorator becomes a miniature private middleware around a single endpoint.

That simplicity hides three sharp mechanisms inside Django 6.1.3: attribute propagation onto the outermost wrapper (used by CsrfViewMiddleware.process_view and LoginRequiredMiddleware), coroutine preservation via inspect.iscoroutinefunction, and the subtle way method_decorator adapts function decorators for class-based views.

What built-in view decorators actually do

Open four of Django’s standard view decorators side by side and notice how consistently they handle both sync and async views in 6.1.3:

Why decorator order and @functools.wraps break silently

Test all three classic decorator failures live on Django 6.1.3:

Recorded on Django 6.1.3 ch04-routing script
View decorators: csrf_exempt stacking, method_decorator, and async wrappers
  csrf_exempt directly -> True; buried under wrapper without @wraps -> False
  @method_decorator(csrf_exempt, name='dispatch').as_view().csrf_exempt -> True
  @method_decorator(csrf_exempt, name='post').as_view().csrf_exempt -> False
  @require_POST on async def -> iscoroutinefunction=True; naive sync decorator on async def -> iscoroutinefunction=False
  GET /post-only/ -> 405 Method Not Allowed Allow='POST'
  POST /post-only/ -> 200 OK body='posted'
  GET /broken/ (sync decorator on async view) -> ValueError: The view __main__.inner didn't return an HttpResponse object. It returned an unawaited coroutine instead. You may need to add an 'await' into your view.

Every line of that recording explains a bug teams spend hours chasing:

  1. Burying @csrf_exempt under a wrapper missing @functools.wraps silently re-enables CSRF. functools.wraps copies the wrapped function’s __dict__ onto the outer wrapper. Omit @functools.wraps in a custom outer decorator stacked above @csrf_exempt, and getattr(callback, "csrf_exempt", False) drops from True to False! CsrfViewMiddleware.process_view inspects the outermost callback, sees no csrf_exempt flag, and rejects every webhook POST with 403 Forbidden.
  2. A synchronous decorator on an async def view breaks coroutine detection. Django’s BaseHandler._get_response and _get_response_async decide whether to await a view (or wrap it in async_to_sync) by calling inspect.iscoroutinefunction(wrapped_callback). When a naive synchronous decorator returns def inner(request): return fn(request), iscoroutinefunction(inner) returns False. Django calls the synchronous wrapper, receives an unawaited coroutine object instead of an HttpResponse, and crashes inside BaseHandler.check_response with ValueError: ... returned an unawaited coroutine instead.!
  3. Stacking order controls short-circuiting and side effects. Put @login_required above @require_POST and an unauthenticated GET gets redirected to the login page (302); reverse them (@require_POST above @login_required) and an unauthenticated GET immediately receives 405 Method Not Allowed without ever touching the session or user table!

Inside method_decorator: why name="dispatch" works and name="post" fails

A function decorator expects (request, *args, **kwargs), whereas a method on a class-based view receives (self, request, *args, **kwargs). method_decorator bridges that signature gap inside _multi_decorate.

Look at the two subtle tricks inside _multi_decorate (lines 39–58 of django/utils/decorators.py):

Now connect that to line 118 of django/views/generic/base.py inside View.as_view:

view.__dict__.update(cls.dispatch.__dict__)

View.as_view copies attributes only from View.dispatch’s __dict__ — never from "get" or "post"! That is why our recording proved @method_decorator(csrf_exempt, name="dispatch").as_view().csrf_exempt -> True, while @method_decorator(csrf_exempt, name="post").as_view().csrf_exempt -> False. Putting csrf_exempt on "post" leaves dispatch unmarked, so CsrfViewMiddleware.process_view never sees the exemption and blocks the POST before dispatch even runs.

Where view decorators leak

That View.as_view copy of View.dispatch’s __dict__ onto the view closure is just one piece of how Django turns Python classes into thread-safe request callables. Let’s open the full class-based view engine and MRO next in View.as_view, MRO, and generic views.