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

# 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`:

- `require_http_methods` (`django/views/decorators/http.py:require_http_methods`, backing `require_GET`, `require_POST`, `require_safe`) inspects `iscoroutinefunction(func)` at decoration time and generates either an `async def inner` or a synchronous `def inner`. On a disallowed verb it returns `HttpResponseNotAllowed` (`405` with an `"Allow"` header) and logs to `"django.request"` before the view ever executes.
- `csrf_exempt` (`django/views/decorators/csrf.py:csrf_exempt`) does *not* bypass CSRF inside its wrapper body at all! It wraps the view function in a pass-through sync or async wrapper, stamps **`csrf_exempt = True`** onto that wrapper object (line 66), and copies metadata via `functools.wraps`. Remember Chapter 3: `CsrfViewMiddleware.process_view` runs *before* the view is called and checks `getattr(callback, "csrf_exempt", False)` on the exact callable returned by `URLResolver.resolve`.
- `login_required` (`django/contrib/auth/decorators.py:login_required`) delegates to `user_passes_test` (`django/contrib/auth/decorators.py:user_passes_test`), which checks `iscoroutinefunction(view_func)`. On an `async def` view, it calls `await request.auser()` and runs `test_func` via `sync_to_async` if needed; on a sync view, it touches `"request.user"`. It also stamps `login_url` and `redirect_field_name` onto the wrapper for `LoginRequiredMiddleware` to inspect.
- `decorator_from_middleware` (`django/utils/decorators.py:decorator_from_middleware`, powering `csrf_protect`, `ensure_csrf_cookie`, `cache_page`, `conditional_page`) wraps a `MiddlewareMixin` class into a per-view decorator inside `make_middleware_decorator` (`django/utils/decorators.py:make_middleware_decorator`), calling `process_request` and `process_view` before the view, `process_exception` on errors, and — when the view returns an unrendered `TemplateResponse` — attaching `process_response` via `SimpleTemplateResponse.add_post_render_callback` so it still runs *after* template rendering!

## Why decorator order and `@functools.wraps` break silently

Test all three classic decorator failures live on Django `6.1.3`:

```text recording=ch04-routing
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`** (`django/utils/decorators.py:method_decorator`) bridges that signature gap inside `_multi_decorate` (`django/utils/decorators.py:_multi_decorate`).

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

- **At request time (lines 39–47):** The returned method wrapper binds `method` to `self`, wraps that bound method in `functools.wraps(method)(functools.partial(method.__get__(self, type(self))))` (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 `@method_decorator(..., name="dispatch")` at **`13.05 us`** versus **`8.97 us`** for an undecorated `View.as_view()` (`+4.08 us` per call!).
- **At import time (lines 16–23 & 50–56):** Because the real bound method does not exist until a request arrives, `_update_method_wrapper` runs each decorator once against a throwaway dummy function and copies its `__dict__` onto the method wrapper, then calls `markcoroutinefunction` on that wrapper if the underlying method is async.

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

```python
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

- **Never put `@csrf_exempt` on `get` or `post` of a CBV.** Always decorate `name="dispatch"` (or wrap the result of `View.as_view` directly in `"urls.py"` with `csrf_exempt(...)`).
- **Custom decorators intended for async views must branch on `inspect.iscoroutinefunction`.** Even adding `@functools.wraps` to a synchronous `def inner` does *not* make the wrapper awaitable — if you wrap an `async def` view, return an `async def` wrapper that `await`s the wrapped coroutine (just as Django's `require_http_methods` and `csrf_exempt` do).
- **`decorator_from_middleware` runs `process_request` AFTER middleware.** Applying `@csrf_protect` or `@cache_page` to a view runs that middleware *inside* the view call, after all global `MIDDLEWARE` layers and `process_view` hooks 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](cbv-dispatch.md).
