from django.views.decorators.csrf import csrf_exempt from django.http import HttpResponse @csrf_exempt def my_view(request): if request.method == 'POST': return HttpResponse('POST received') return HttpResponse('Hello')
The @csrf_exempt decorator disables CSRF protection for the decorated view. Therefore, POST requests without a CSRF token are accepted and processed normally.
<form method="post"> <!-- CSRF token goes here --> <input type="text" name="username"> <button type="submit">Submit</button> </form>
The correct way to include the CSRF token in a Django template form is using the {% csrf_token %} template tag. It inserts a hidden input with the token automatically.
views.py: from django.shortcuts import render from django.views.decorators.csrf import csrf_protect @csrf_protect def submit_view(request): if request.method == 'POST': return render(request, 'success.html') return render(request, 'form.html') form.html: <form method="post"> <input type="text" name="data"> <button type="submit">Send</button> </form>
The CSRF protection requires the token to be included in the form. The template lacks {% csrf_token %}, so Django rejects the POST request.
Django stores a CSRF token in a cookie and expects the same token to be sent in the POST data. It compares these tokens to verify the request.
from django.shortcuts import render def my_view(request): return render(request, 'page.html')
Django sets the CSRF cookie with a new token on safe HTTP methods like GET if the cookie is missing, to prepare for future POST requests.
