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:
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?
There is a section of Django's CSRF Protection documentation titled View needs protection for one path which describes a solution. The idea is to use @csrf_exempt
on the whole view, but when the API client header is not present or invalid, then call a function
annotated with @csrf_protect
.