By default, Django offers CSRF protection to secure your website from cross site requests. However, in some cases you may need to disable CSRF protection to be able to accept and process requests from other website domains. In this article, we will look at how to disable CSRF validation in Django view.
What is CSRF Validation
How to Disable CSRF validation in Django View
Here are the steps to disable CSRF validation in Django view. There are a couple of ways to disable CSRF protection in Django.
1. Using @csrf_exempt decorator
CSRF protection is enabled by default for all Django views. If you want to disable CSRF protection for one or more views, but not all views then add the following line in that view’s views.py file
from django.views.decorators.csrf import csrf_exempt
The is will import the @csrf_exempt decorator that allows you to easily disable CSRF validation for specific views. Just place @csrf_exempt decorator immediately above the view for which you do not want CSRF protection.
@csrf_exempt def my_view(request): return HttpResponse('Hello world')
So your views.py file will look like
from django.views.decorators.csrf import csrf_exempt... @csrf_exempt def my_view(request): return HttpResponse('Hello world')
2. Disable CSRF middleware
If you want to disable CSRF protection for all views, simply comment (by adding # at its beginning) or delete CSRF middleware from settings.py file.
MIDDLEWARE = [ ... #
However, please note, CSRF protection is a very good security measure and you must not disable it for all views on your site, unless it is absolutely necessary. The recommended way to disable CSRF validation is to use the @csrf_exempt decorator only for views where you don’t want it, as shown above.