How to Use Django’s CSRF Middleware?
We need to add django.middleware.csrf.CsrfViewMiddleware in the settings.py file to enable it. By default, Django already has this enabled, as in the following example:
Let us create HTML page in which usersubmits a form. We have included the {%csrf_token%} as a hidden field in our HTML code.
HTML file
HTML
< form method = "post" > {% csrf_token %} < form action = "/your-name/" method = "post" > < label for = "your_name" >Your name: </ label > < input id = "your_name" type = "text" name = "your_name" value = "{{ current_name }}" > < button type = "submit" >Submit</ button > </ form > |
The CSRF Decorator Method
When we want that our CSRF should work only for particular view then we can use Decorator method in which have to place ‘@csrf_protect’ at the top of that function as shown below in the views.py file
Views.py
Python3
from django.http import HttpResponse from django.views.decorators.csrf import csrf_protect @csrf_protect def simulate_csrf_error(request): if request.method = = 'POST' : return HttpResponse( "Form submitted successfully!" ) return HttpResponse( "GET request, please submit the form." ) |
CSRF token in Django
Django provides a feature known as a CSRF token to get away from CSRF attacks that can be very dangerous. when the session of the user starts on a website, a token is generated which is then cross-verified with the token present with the request whenever a request is being processed.
Contact Us