0
0
DjangoDebug / FixBeginner · 3 min read

How to Fix CSRF Verification Failed Error in Django

The 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.

html
<form method="post" action="/submit/">
  <input type="text" name="name" />
  <button type="submit">Send</button>
</form>
Output
Forbidden (403) CSRF verification failed. Request aborted.
🔧

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.

html
<form method="post" action="/submit/">
  {% csrf_token %}
  <input type="text" name="name" />
  <button type="submit">Send</button>
</form>
Output
Form submits successfully without CSRF errors.
🛡️

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.

Key Takeaways

Always include {% csrf_token %} inside POST forms in Django templates.
Ensure CSRF middleware is enabled in your Django settings.
Send CSRF tokens in AJAX request headers to avoid verification errors.
Do not disable CSRF protection unless you understand the security risks.
Check cookies and sessions if CSRF errors persist unexpectedly.