How To Enable Or Disable CSRF Validation In Django Web Application

Django has provide a feature that can help you to avoid csrf attack on your Django application. But some times especially in your development environment, you do not want this feature when send post request to your web server use curl in command line, if this feature enabled, you will get errors. This article will tell you how to enable or disable csrf validation in Django application.

1. Enable CSRF.

The csrf function is enabled by default in Django app. So if you do not disable it before, it is enabled by default. If you want to pass the csrf validation in your django code, you can add below code in your template html page form web element.

 <form method="post" action="{% url 'dept_emp:user_add' %}">
   ......
   <!-- avoid CSRF verification failed error. -->
   {% csrf_token %}
   ......
</form>

If you use curl to send a POST request to your Django web app when csrf validation is enabled, you will get bellow error.

:~$ curl -i -X POST  http://127.0.0.1:8000/dept_emp/test_class_based_view
HTTP/1.1 403 Forbidden
Date: Wed, 03 Apr 2019 08:49:21 GMT
Server: WSGIServer/0.2 CPython/3.6.7
Content-Type: text/html
X-Frame-Options: SAMEORIGIN
Content-Length: 2868


<!DOCTYPE html>
<html lang="en">
<head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <meta name="robots" content="NONE,NOARCHIVE">
  ......

</html>

2. Disable CSRF Validation.

2.1 Disable CSRF Validation For Entire Django Project.

django project app dept_emp source files structure

  1. Edit django project settings.py file ( DjangoHelloWorld / DjangoHelloWorld / settings.py ).
  2. Comment or remove ‘django.middleware.csrf.CsrfViewMiddleware’ in MIDDLEWARE list then csrf validation has been removed from this django app. All post request in this django project without csrf tag will not meet error.
    MIDDLEWARE = [
        ......
        #'django.middleware.csrf.CsrfViewMiddleware',
        ......
    ]
    

2.2 Disable CSRF Validation For Class Based View.

You can also disable csrf validation for single class based view use method_decorator and csrf_exempt.

from django.views.decorators.csrf import csrf_exempt

from django.utils.decorators import method_decorator

@method_decorator(csrf_exempt, name='dispatch')
class TestClassBasedView(View):

    def get(self, request):
       ......

2.3 Disable CSRF Validation For Function Based View.

Below code will disable csrf validation for single function based view use csrf_exempt.

from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def test_function_based_view(request):

    if(request.method=='GET'):

         ......
READ :   How To Add Models To Django Admin Site

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.