I am trying to send an HTTPS PUT request to a RESTful API Django web service using a djangorestframework (DRF: http://django-rest-framework.org/) View. I cannot get this to work due to Django’s Cross Site Request Forgery (CSRF) protection.
The PUT request is intended to allow unauthenticated users to add a resource.
What I have considered/tried:
- Disabling CSRF — not acceptable. The API runs on the same Django instance as the non-API service. Disabling CSRF protection is too much risk.
- Using the
X-Requested-With: XMLHttpRequestheader on the PUT request (I control the clients). Doesn’t work — I still get the CSRF error. - Using the
@crsf_exemptdecorator on the PUT view. I would if I could — the framework defines a class, not a view.
My current best option is to write PUT views myself without using DRF’s View class. I can then use the @crsf_exempt decorator successfully.
I’d like to use DRF’s View class — but cannot see how. Can you?
Thanks to James Cran Wellward, I was also able to solve this issue by using the method_decorator.
and then test it:
returns:
and
returns:
HTH. see the original post.