Skip to main content

Command Palette

Search for a command to run...

Fixing 'CSRF Verification Failed' in Django

Updated
•2 min read•View as Markdown
U
Software engineer & founder of Djangix (djangix.com). Django/Python backends, deployment, payments, AI automation.

Originally published on the Djangix blog. This is a condensed version — read the full article on djangix.com at the link below.

“CSRF verification failed” is Django protecting you — a POST arrived without a valid CSRF token. Work through the causes below in order; one of them is almost always responsible.

1. Missing csrf_token in the form

Every POST form rendered by Django needs the CSRF token tag inside it. Without it, the browser sends no token and the middleware rejects the request with a 403. This is the first thing to check, especially on hand-written templates and forms added by JavaScript.

2. CSRF_TRUSTED_ORIGINS behind proxies

In production behind a proxy or load balancer, Django may see a different scheme or host than the browser used. If the Origin does not match a trusted pattern, the check fails even with a correct token. Add your real production origin — including https:// — to CSRF_TRUSTED_ORIGINS.

If the CSRF cookie never reaches the server, no token can validate. Check cookie domain and secure flags against how the site is actually served, and confirm the cookie is being set in the browser at all before blaming the form.

4. The AJAX header

JavaScript requests do not get the template tag automatically. Read the token from the cookie or the rendered page and send it in the X-CSRFToken header on every POST, PUT, and DELETE request.

Read the full article

This was a condensed summary. The complete troubleshooting guide is on the Djangix blog: Fixing 'CSRF Verification Failed' in Django

More from this blog

D

Djangix

14 posts