How to Fix CSRF Verification Failed Error in Django
CSRF verification failed error in Django happens when the CSRF token is missing or incorrect in a POST request. To fix it, ensure your HTML form includes {% csrf_token %} inside the form tag and that the CSRF middleware is enabled in your settings.Why This Happens
Django protects your site from malicious POST requests by requiring a CSRF token. This token must be sent with every POST form submission. If the token is missing or does not match, Django raises a CSRF verification failed error.
This often happens when the form does not include the CSRF token or when the request is made without proper headers, such as in AJAX calls without the token.
<form method="post" action="/submit/"> <input type="text" name="name" /> <button type="submit">Send</button> </form>
The Fix
Add the {% csrf_token %} template tag inside your form to include the CSRF token. This token is required for Django to verify the request is safe.
Also, make sure django.middleware.csrf.CsrfViewMiddleware is enabled in your MIDDLEWARE settings.
<form method="post" action="/submit/"> {% csrf_token %} <input type="text" name="name" /> <button type="submit">Send</button> </form>
Prevention
Always include {% csrf_token %} in every POST form in your Django templates. For AJAX requests, send the CSRF token in the request headers.
Keep the CSRF middleware enabled and avoid disabling it unless absolutely necessary. Use Django's built-in template tags and helpers to manage CSRF tokens automatically.
Related Errors
Other common errors include:
- CSRF cookie not set: Happens if cookies are disabled or not sent.
- CSRF token missing in AJAX: Fix by adding the token to AJAX headers.
- Session expired: User session expired causing token mismatch.