DEV Community

Ubaid Ullah
Ubaid Ullah

Posted on Originally published at djangix.com

Fixing 'CSRF Verification Failed' in Django

Originally published on the Djangix blog: Fixing 'CSRF Verification Failed' in Django

Few Django errors stop a form submission as abruptly as “CSRF verification failed.” It usually does not mean your site is under attack — it means Django could not find or validate the CSRF token it expected. Work through the common causes in order.

First, check the form itself: every POST form in a Django template needs the {% csrf_token %} tag inside it, so the token is submitted with the form. Second, if your site runs behind a proxy or is served over HTTPS, add your real domain to CSRF_TRUSTED_ORIGINS — Django needs to know which origins to trust for secure requests. Third, review your cookie settings: overly strict or mismatched CSRF and session cookie settings can stop the token cookie from being sent or read correctly.

Finally, the AJAX case: when you submit with JavaScript instead of a plain form, the token is not sent automatically. Read the token from the cookie or the page and send it in the X-CSRFToken header with your request. Once you match the case that fits your setup, the error should clear.

Full article: Fixing 'CSRF Verification Failed' in Django

Top comments (0)