I'm trying to write a site in Django where the API URLs are the same as user-facing URLs. But I'm having trouble with pages which use POST requests and CSRF protection. For example, if I have a page /foo/add I want to be able to send POST requests to it in two ways:
- As an end user (authenticated using a session cookie) submitting a form. This requires CSRF protection.
- As an API client (authenticated using a HTTP request header). This will fail if CSRF protection is enabled.
I have found various ways of disabling CSRF, such as @csrf_exempt, but these all disable it for the entire view. Is there any way of enabling/disabling it at a more fine-grained level? Or am I just going to have to implement by own CSRF protection from scratch?
Best Answer
Modify
urls.py
If you manage your routes in
urls.py
, you can wrap your desired routes withcsrf_exempt()
to exclude them from the CSRF verification middleware.for instance,
Alternatively, as a Decorator
Some may find the use of the
@csrf_exempt
decorator more suitable for their needsfor instance,