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 and LoginRequiredMiddleware), coroutine preservation via inspect, 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:
require_http_methods(require_http_methods, backingrequire_GET,require_POST,require_safe) inspectsiscoroutinefunction(func)at decoration time and generates either anasync def inneror a synchronousdef inner. On a disallowed verb it returnsHttpResponseNotAllowed(405with an"Allow"header) and logs to"django.request"before the view ever executes.csrf_exemptdoes not bypass CSRF inside its wrapper body at all! It wraps the view function in a pass-through sync or async wrapper, stampscsrf_exempt = Trueonto that wrapper object (line 66), and copies metadata viafunctools.wraps. Remember Chapter 3:CsrfViewMiddlewareruns before the view is called and checks.process_view getattr(callback, "csrf_exempt", False)on the exact callable returned byURLResolver..resolve login_requireddelegates touser_passes_test, which checksiscoroutinefunction(view_func). On anasync defview, it callsawait requestand runs.auser() test_funcviasync_to_asyncif needed; on a sync view, it touches"request.user". It also stampslogin_urlandredirect_field_nameonto the wrapper forLoginRequiredMiddlewareto inspect.decorator_from_middleware(decorator_from_middleware, poweringcsrf_protect,ensure_csrf_cookie,cache_page,conditional_page) wraps aMiddlewareMixinclass into a per-view decorator insidemake_middleware_decorator, callingprocess_requestandprocess_viewbefore the view,process_exceptionon errors, and — when the view returns an unrenderedTemplateResponse— attachingprocess_responseviaSimpleTemplateResponseso it still runs after template rendering!.add_post_render_callback
Why decorator order and @functools.wraps break silently
Test all three classic decorator failures live on Django 6.1.3:
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:
- Burying
@csrf_exemptunder a wrapper missing@functools.wrapssilently re-enables CSRF.functools.wrapscopies the wrapped function’s__dict__onto the outer wrapper. Omit@functools.wrapsin a custom outer decorator stacked above@csrf_exempt, andgetattr(callback, "csrf_exempt", False)drops fromTruetoFalse!CsrfViewMiddlewareinspects the outermost callback, sees no.process_view csrf_exemptflag, and rejects every webhook POST with403 Forbidden. - A synchronous decorator on an
async defview breaks coroutine detection. Django’sBaseHandlerand._get_response _get_response_asyncdecide whether toawaita view (or wrap it inasync_to_sync) by callinginspect. When a naive synchronous decorator returns.iscoroutinefunction(wrapped_callback) def inner(request): return fn(request),iscoroutinefunction(inner)returnsFalse. Django calls the synchronous wrapper, receives an unawaited coroutine object instead of anHttpResponse, and crashes insideBaseHandlerwith.check_response ValueError: ... returned an unawaited coroutine instead.! - Stacking order controls short-circuiting and side effects. Put
@login_requiredabove@require_POSTand an unauthenticated GET gets redirected to the login page (302); reverse them (@require_POSTabove@login_required) and an unauthenticated GET immediately receives405 Method Not Allowedwithout 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/):
- At request time (lines 39–47): The returned method wrapper binds
methodtoself, wraps that bound method infunctools(because Python refuses to set arbitrary attributes on bound-method objects, only on functions and partials!), applies every decorator in the list, and invokes the result. That per-request re-binding is why our Chapter 4 benchmark measured.wraps(method)(functools .partial(method .__get__(self, type(self)))) @method_decorator(..., name="dispatch")at13.05 usversus8.97 usfor an undecoratedView.as_view()(+4.08 usper call!). - At import time (lines 16–23 & 50–56): Because the real bound method does not exist until a request arrives,
_update_method_wrapperruns each decorator once against a throwaway dummy function and copies its__dict__onto the method wrapper, then callsmarkcoroutinefunctionon that wrapper if the underlying method is async.
Now connect that to line 118 of django/ 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 never sees the exemption and blocks the POST before dispatch even runs.
Where view decorators leak
- Never put
@csrf_exemptongetorpostof a CBV. Always decoratename="dispatch"(or wrap the result ofView.as_viewdirectly in"urls.py"withcsrf_exempt(...)). - Custom decorators intended for async views must branch on
inspect. Even adding.iscoroutinefunction @functools.wrapsto a synchronousdef innerdoes not make the wrapper awaitable — if you wrap anasync defview, return anasync defwrapper thatawaits the wrapped coroutine (just as Django’srequire_http_methodsandcsrf_exemptdo). decorator_from_middlewarerunsprocess_requestAFTER middleware. Applying@csrf_protector@cache_pageto a view runs that middleware inside the view call, after all globalMIDDLEWARElayers andprocess_viewhooks have already executed.
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.