Django form POST returns 403 Forbidden: CSRF verification failed
Forbidden (403)Short answer
Django rejects an unsafe request when the CSRF cookie or the form token is missing or wrong, or when the Origin or Referer check fails. The reason text on the 403 page and the django.security.csrf log line tell you which. Common fixes: add {% csrf_token %} to the form, list your HTTPS origin in CSRF_TRUSTED_ORIGINS, and reload the form after login.
Fix it fast
1Find out which cause you have
Read the reason line. Django prints it on the 403 page when DEBUG is on, and logs a warning to the django.security.csrf logger always.
grep -R 'django.security.csrf\|CSRF' /var/log/gunicorn/ /var/log/app/ 2>/dev/null | tail -n 202Match what you see, then jump to its fix
- 1
Reason says the CSRF token is missing or incorrect, and the HTML of the form has no csrfmiddlewaretoken fieldThe form has no CSRF tokenFix - 2
The reason line mentions the Origin check, and the form is served over HTTPS from a host that is not in CSRF_TRUSTED_ORIGINSOrigin checking failed behind an HTTPS proxy or on another host nameFix - 3
The reason line mentions the Referer check, and the POST goes to an HTTPS URL from a page with a no-referrer policyThe Referer header is stripped on an HTTPS siteFix - 4
Reason says the CSRF cookie is not set, and the browser's cookie list has no csrftoken for the siteThe CSRF cookie is never stored or is not sent backFix - 5
Fails only after signing in, or after using the back buttonThe form was loaded before login or logoutFix
- 1
What does the error look like?
Forbidden (403)CSRF verification failed. Request aborted.
Cause 1 of 5
The form has no CSRF token
1Check
Unsafe methods (POST, PUT, PATCH, DELETE) need the csrfmiddlewaretoken form field and the CSRF cookie. View the page source of the form.
curl -s -c /tmp/jar https://app.example.com/contact/ | grep -i csrfmiddlewaretoken2Fix
Put the template tag inside every POST form that posts to your own site. Do not put it in forms that post to other domains.
<form method="post" action="/contact/">
{% csrf_token %}
<input name="email">
<button type="submit">Send</button>
</form>3Verify
The rendered HTML now has a hidden csrfmiddlewaretoken input and the POST returns 200 or a redirect.
curl -s -c /tmp/jar https://app.example.com/contact/ | grep -c csrfmiddlewaretokenConfirmed by docs.djangoproject.com
Cause 2 of 5
Origin checking failed behind an HTTPS proxy or on another host name
1Check
Django requires the Origin header to match the Host origin. Behind a proxy that terminates TLS, Django may see plain HTTP and build a different origin, so a form served from https://app.example.com fails.
python manage.py shell -c "from django.conf import settings as s; print(s.CSRF_TRUSTED_ORIGINS, s.SECURE_PROXY_SSL_HEADER, s.ALLOWED_HOSTS)"2Fix
Add each public origin, with its scheme, to CSRF_TRUSTED_ORIGINS. If a proxy sets X-Forwarded-Proto, and only if it strips that header from incoming requests, tell Django to trust it.
# settings.py
CSRF_TRUSTED_ORIGINS = ["https://app.example.com", "https://*.example.com"]
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")3Verify
Restart the app and repeat the POST from the browser.
sudo systemctl restart gunicornConfirmed by docs.djangoproject.com
Cause 3 of 5
The Referer header is stripped on an HTTPS site
1Check
Over HTTPS, a request without an Origin header needs a matching Referer. A page with Referrer-Policy: no-referrer (or a meta referrer tag) removes it.
curl -sI https://app.example.com/contact/ | grep -i referrer-policy
grep -R "no-referrer" templates/ 2>/dev/null2Fix
Stop sending no-referrer on pages that POST to your own site. Use rel="noreferrer" on links to third-party sites instead.
<meta name="referrer" content="same-origin">
<a href="https://other.example.net" rel="noreferrer">partner</a>3Verify
Reload the form and submit it; the 403 is gone.
curl -sI https://app.example.com/contact/ | grep -i referrer-policyConfirmed by docs.djangoproject.com
Cause 4 of 5
The CSRF cookie is never stored or is not sent back
1Check
A cookie marked Secure is only sent over HTTPS, so CSRF_COOKIE_SECURE = True on a plain HTTP development server breaks every POST. Cookies blocked by the browser, or a CSRF_COOKIE_DOMAIN that does not cover the host, have the same effect.
python manage.py shell -c "from django.conf import settings as s; print(s.CSRF_COOKIE_SECURE, s.CSRF_COOKIE_DOMAIN, s.CSRF_COOKIE_SAMESITE)"2Fix
Serve the site over HTTPS, or set CSRF_COOKIE_SECURE to False only in local development. Set CSRF_COOKIE_DOMAIN to None or a domain that covers the page.
# settings_dev.py
CSRF_COOKIE_SECURE = False
CSRF_COOKIE_DOMAIN = None3Verify
The csrftoken cookie appears in the browser's storage after loading the form.
curl -s -D - -o /dev/null http://localhost:8000/contact/ | grep -i set-cookieConfirmed by docs.djangoproject.com
Cause 5 of 5
The form was loaded before login or logout
1Check
Django rotates CSRF tokens at login. A form rendered earlier still holds the old token.
# Reproduce: open the form, sign in from another tab, then submit the first tab2Fix
Reload the page to get a fresh token. For pages that stay open a long time, show a message that asks the user to refresh.
# no code change needed; reload the form page before submitting3Verify
A form loaded after login submits successfully.
# Submit the freshly loaded formConfirmed by docs.djangoproject.com
How do I stop it coming back?
- Keep CsrfViewMiddleware in MIDDLEWARE and never use @csrf_exempt to silence an error.
- Set CSRF_TRUSTED_ORIGINS with the scheme in every environment that has its own host name.
- Test one real form POST over HTTPS in staging after every proxy or domain change.
- Set CSRF_FAILURE_VIEW to a page that tells users to reload.
Sources
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.
Which stack is behind this page?
Projects of mine built on the same technologies:
- stegnor.comMy company site: 804 pages from a Python and Jinja generator, with 15 free browser tools.
- TaxiDexMy own multi-tenant taxi dispatch SaaS: API, dispatcher portal, driver and passenger apps, and the servers underneath.
- MenuloA restaurant discovery platform in Germany, kept current by a Python ingestion pipeline.
Related fixes
Back end
Django returns 403 for a fetch or AJAX POST because the CSRF token is not sent
403 Forbidden on an XMLHttpRequest or fetch POST to a Django view
A JavaScript POST has no form field, so Django needs the token in the X-CSRFToken header.
4 causes, each with a fixBack end
Airflow SSHOperator stops a long script with SSH command timed out
airflow.exceptions.AirflowException: SSH command timed out
SSHOperator waits only 10 seconds for a command by default.
3 causes, each with a fixBack end
Python asyncio: Task was destroyed but it is pending
RuntimeWarning: coroutine '...' was never awaited
A task was still unfinished when Python threw it away.
4 causes, each with a fixBack end
Celery in a Django project does not connect to Redis or ignores the broker URL
kombu.exceptions.InconsistencyError: ... _kombu.binding.celery
Celery talks to Redis through a client library and reads its broker URL from your Django settings.
4 causes, each with a fixBack end
Chrome shows net::ERR_INCOMPLETE_CHUNKED_ENCODING on a PHP page
The page loads partly, then the response stops
The browser got a chunked response that ended before its final zero-length chunk, so the connection closed mid-page.
2 causes, each with a fixBack end
CodeIgniter works locally but every page is 404 on the live server
The requested URL was not found on this server.
A 404 on the live server comes from one of four places: the document root is not the public folder, Apache ignores .htaccess or nginx has no try_files rule, the route is not defined because auto routing is off, or the controller file name differs from its class in case.
5 causes, each with a fix