How to Prevent CSRF in Django: Simple Fix and Best Practices
CsrfViewMiddleware and include the {% csrf_token %} tag inside your HTML forms. This ensures that every POST request has a valid token that Django checks to block unauthorized requests.Why This Happens
CSRF (Cross-Site Request Forgery) happens when a malicious website tricks a user's browser into sending unwanted requests to your Django site without the user's consent. This can cause harmful actions like changing user data or making purchases.
If you do not protect your forms with CSRF tokens, Django cannot verify if the request is from a trusted source, leaving your site vulnerable.
from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt @csrf_exempt def unsafe_view(request): if request.method == 'POST': # Process form data without CSRF protection return render(request, 'success.html') return render(request, 'form.html')
The Fix
Enable Django's CSRF protection by removing @csrf_exempt and ensuring CsrfViewMiddleware is active in your settings.py. Also, add {% csrf_token %} inside your HTML form to include the token in POST requests.
from django.shortcuts import render def safe_view(request): if request.method == 'POST': # Process form data safely return render(request, 'success.html') return render(request, 'form.html')
Prevention
Always keep CsrfViewMiddleware enabled (it is by default in Django). Use the {% csrf_token %} tag inside every POST form in your templates. Avoid disabling CSRF protection unless absolutely necessary.
Use Django’s csrf_protect decorator for views that need explicit protection. Regularly test your forms to ensure tokens are included and validated.
Related Errors
Common related errors include:
- 403 Forbidden CSRF verification failed: Happens when the CSRF token is missing or invalid in a POST request.
- Missing CSRF token in AJAX requests: You must include the CSRF token in AJAX headers or data.
Fix these by adding {% csrf_token %} in forms and configuring AJAX to send the token.