Forbidden (403) CSRF verification failed. Request aborted. — Django after deploy
Forbidden (403) CSRF verification failed. Request aborted. means Django's CSRF middleware refused a POST. Right after moving behind HTTPS and a proxy, the usual reason is Origin checking failed: add the site's origin with its scheme, such as https://example.com, to CSRF_TRUSTED_ORIGINS. For CSRF cookie not set or CSRF token missing, put the csrf_token tag in the form or send the X-CSRFToken header.
By Livops team, the people who build and run LivopsUpdated
What the visitor sees, in production with DEBUG off[6][7]:
Forbidden (403)
CSRF verification failed. Request aborted.
More information is available with DEBUG=True.
The reason is in one of these lines, which Django logs, or shows under “Reason given for failure” when DEBUG is on[5][7]:
Forbidden (Origin checking failed - https://shop.example.com does not match any trusted origins.): /accounts/login/
Forbidden (CSRF cookie not set.): /accounts/login/
Forbidden (CSRF token missing.): /api/orders/
This page explains the checks behind the error, gives the fix for each reason, from the one that appears on the first deploy behind HTTPS, and shows how to test the fix before deploying again.
What does the error mean?
Django’s CsrfViewMiddleware checks every request that is not GET, HEAD, OPTIONS or TRACE[1]. It checks, in this order[5]:
- The
Originheader, if the browser sent one. It must equal the scheme and host Django thinks it is serving,httpsifrequest.is_secure()is true andhttpif not, or match an entry ofCSRF_TRUSTED_ORIGINS[5]. - The
Refererheader, for HTTPS requests that arrived withoutOrigin. Django does strict referer checking on them[1]. - The cookie and the token. The
csrftokencookie must be present, and the token must come in the form fieldcsrfmiddlewaretokenor, failing that, in theX-CSRFTokenheader[5].
The first check that fails ends the request with a 403[1]. With DEBUG off, the page leaves the reason out[7], and Django’s default logging sends its messages to the console only when DEBUG is on[8]. To see the reason in your logs, send the CSRF logger to the console:
LOGGING = {
"version": 1,
"disable_existing_loggers": False,
"handlers": {"csrf_console": {"class": "logging.StreamHandler"}},
"loggers": {
"django.security.csrf": {"handlers": ["csrf_console"], "level": "WARNING", "propagate": False},
},
}
Causes, most common first
1. Origin checking failed, behind HTTPS
Origin checking failed - https://shop.example.com does not match any trusted origins.
This is the one that appears after the first deploy. The browser posts the form from https://shop.example.com and says so in Origin. A platform or a reverse proxy takes the HTTPS connection and passes the request on to Django over plain HTTP, and then is_secure() returns False even for requests the visitor made over HTTPS[3]. Django builds the origin it expects as http://shop.example.com, the two strings differ, and the POST is refused[5]. Locally everything is http://, so you never see it there. The admin login is usually the first form to fail.
Fix: list the origins in CSRF_TRUSTED_ORIGINS. The setting is the list of trusted origins for unsafe requests, and it accepts subdomain wildcards such as https://*.example.com[3]. Since Django 4.0 each value must include the scheme, and a value that started with a dot is now written with an asterisk: .example.com becomes https://*.example.com[4].
CSRF_TRUSTED_ORIGINS = ["https://shop.example.com", "https://www.shop.example.com"]
An entry without a wildcard is compared with the Origin header as a whole string[5], so write it the way a browser sends it: scheme and host, a port only if the address has one, no path and no trailing slash. To keep one list of domains, build the origins from ALLOWED_HOSTS, turning a leading dot into a wildcard:
CSRF_TRUSTED_ORIGINS = [
"https://" + ("*" + host if host.startswith(".") else host)
for host in ALLOWED_HOSTS
if host and host != "*"
]
The other fix: tell Django the request was HTTPS. SECURE_PROXY_SSL_HEADER makes is_secure() trust a header from your proxy, usually ("HTTP_X_FORWARDED_PROTO", "https"), and then the origin matches without being listed[3]. Django’s warning is explicit: set it only if your app is behind a proxy that strips X-Forwarded-Proto from incoming requests and sets it only for requests that came in over HTTPS; otherwise keep it None[3]. A forged header would make plain HTTP look secure. The same setting is the cure when SECURE_SSL_REDIRECT = True causes an endless redirect behind a proxy[3]. Once requests count as secure, those without an Origin header also go through the strict Referer check[1].
2. CSRF cookie not set
CSRF cookie not set.
The POST arrived without the csrftoken cookie[5]. This is the one reason the production 403 page explains by itself, with a note that the site needs a CSRF cookie to accept forms[7]. The usual causes:
CSRF_COOKIE_SECURE = Trueon plain HTTP. A secure cookie may be sent by browsers only over HTTPS[3]. Turn it on once the site is on HTTPS, as the deployment checklist says[9], but not for a test overhttp://. Tie it to the environment:CSRF_COOKIE_SECURE = not DEBUG.- The page never set the cookie. Django sets it when a template uses the
csrf_tokentag. A page that adds its forms with JavaScript, or one that posts with AJAX and has no form, may get no cookie; putensure_csrf_cookieon the view that sends the page[2]. - The form is on another site. The cookie’s
SameSiteflag isLaxby default, which keeps it out of cross-site requests[3]. A form on another domain, or your page inside someone else’s frame, posts without it.
3. CSRF token missing
CSRF token missing.
The cookie arrived, but neither the form field nor the header did[5]. In a template, every POST form to your own site needs the tag; never put it in a form that posts to an external URL, because that leaks the token[2]:
<form method="post">
{% csrf_token %}
...
</form>
For fetch or another AJAX request, send the token in the X-CSRFToken header[2]. Read it from the csrftoken cookie; if CSRF_COOKIE_HTTPONLY or CSRF_USE_SESSIONS is on, render the csrf_token tag and read the hidden field from the page instead[2]:
const csrftoken = document.cookie
.split("; ")
.find((c) => c.startsWith("csrftoken="))
?.split("=")[1];
fetch("/api/orders/", {
method: "POST",
headers: { "X-CSRFToken": csrftoken, "Content-Type": "application/json" },
body: JSON.stringify(order),
mode: "same-origin", // do not send the token to another domain
});
If your client uses another header name, CSRF_HEADER_NAME must name it in request.META form: X-XSRF-TOKEN becomes HTTP_X_XSRF_TOKEN[3].
4. CSRF token from POST incorrect
A token arrived but does not match the cookie. For a header the message reads CSRF token from the 'X-Csrftoken' HTTP header incorrect.[5] Two usual causes: the token is rotated at login, so a form opened before logging in elsewhere, or reached with the back button after a login, is stale[7]; and a view cached with cache_page that was cached without its CSRF cookie, which csrf_protect under the cache decorator prevents[2].
5. Referer checking failed - no Referer
An HTTPS request with no Origin and no Referer. Strict referer checking needs the header, so a Referrer-Policy: no-referrer header or <meta name="referrer" content="no-referrer"> breaks the form; use rel="noreferrer" on links to other sites instead[1][7].
How to confirm the fix locally
Run with production settings and post the way the browser will, with an HTTPS origin, to a form view:
DEBUG=1 ALLOWED_HOSTS=shop.example.com python manage.py runserver 127.0.0.1:8000
curl -s -X POST -H "Host: shop.example.com" -H "Origin: https://shop.example.com" \
http://127.0.0.1:8000/accounts/login/ | grep -A 3 "Reason given"
Before the fix the reason is Origin checking failed. After adding https://shop.example.com to CSRF_TRUSTED_ORIGINS it becomes CSRF cookie not set.: curl sent no cookie, so this is the expected next check[5], and the origin is now trusted. This assumes your settings read DEBUG and ALLOWED_HOSTS from the environment. python manage.py check --deploy, run against the production settings, automates some of the deployment checklist, the list that also asks for CSRF_COOKIE_SECURE[9].
On Livops
- Every address is HTTPS. The project’s
<name>.livops.appaddress gets HTTPS automatically, and a domain you connect gets its certificate as soon as it is live. Your app itself listens on the port inPORT; there is no certificate to set up in Django. ALLOWED_HOSTSis set for you. For a Python web app, Livops sets theALLOWED_HOSTSvariable to the project’s addresses, comma-separated, unless you set it yourself. Read it insettings.py, and buildCSRF_TRUSTED_ORIGINSfrom it as in cause 1; if you setALLOWED_HOSTS=.livops.appyourself, the same lines turn it intohttps://*.livops.app.SECURE_PROXY_SSL_HEADERonly on evidence. Set it only after you have checked which header reaches your app and that a visitor cannot forge it, as Django’s warning asks.CSRF_TRUSTED_ORIGINSdoes not depend on any header.- Settings from Variables. Put
SECRET_KEYandDEBUGin the service’s Variables, and deploy again after changing them. - The reason in Logs. With the
LOGGINGlines above, each refused POST prints its reason on the project’s Logs page.
What Livops does for Django: Frameworks. The check that comes before this one: DisallowedHost: Invalid HTTP_HOST header. The whole production setup: Django hosting.
Questions
Why do forms work locally and fail with a CSRF error after deploy?
Locally the browser and Django both see http://127.0.0.1:8000, so the Origin header matches. In production the browser sends https://your-domain, while Django behind a proxy may see the request as plain HTTP and expect http://your-domain. The two differ, and the POST is refused.
Does CSRF_TRUSTED_ORIGINS need https:// in it?
Yes. Since Django 4.0 every value must include the scheme, for example https://example.com, and a value for all subdomains is written https://*.example.com instead of .example.com.
Should I set SECURE_PROXY_SSL_HEADER or CSRF_TRUSTED_ORIGINS?
CSRF_TRUSTED_ORIGINS is the safe first fix: it depends on nothing but your domain list. SECURE_PROXY_SSL_HEADER is right only if your proxy sets the header for HTTPS requests and strips it from incoming ones; Django warns that setting it otherwise can compromise the site.
Why does the 403 page not say what went wrong?
With DEBUG off, Django's page shows only the general message; the reason is printed only when DEBUG is True. Django's default logging also sends its messages to the console only with DEBUG on, so add a logger for django.security.csrf to see the reason in your logs.
I added CSRF_TRUSTED_ORIGINS and now see CSRF cookie not set. Is that progress?
Yes. The origin check passed, and Django moved on to the next one. Check that the page with the form sets the cookie, and that CSRF_COOKIE_SECURE is not on while you test over plain http.
Can I just add csrf_exempt to the view?
Only for a view that really takes no browser session, such as a webhook that checks its own signature. On a login form or the admin it removes the protection instead of fixing the configuration.
What does Livops set up for Django?
It sets the ALLOWED_HOSTS variable to the project's addresses unless you set it yourself, runs migrate before every start and collectstatic during the build when STATIC_ROOT is set. Every address is served over HTTPS.
Sources
- Django docs — Cross Site Request Forgery protection (docs.djangoproject.com). Checked .
- Django docs — How to use Django's CSRF protection (docs.djangoproject.com). Checked .
- Django docs — Settings (docs.djangoproject.com). Checked .
- Django docs — Django 4.0 release notes (docs.djangoproject.com). Checked .
- Django source — django/middleware/csrf.py (6.1) (raw.githubusercontent.com). Checked .
- Django source — django/views/csrf.py (6.1) (raw.githubusercontent.com). Checked .
- Django source — django/views/templates/csrf_403.html (6.1) (raw.githubusercontent.com). Checked .
- Django docs — Logging (docs.djangoproject.com). Checked .
- Django docs — Deployment checklist (docs.djangoproject.com). Checked .
Put your project online today
Connect GitHub or drop a folder. No card is asked for.
Deploy your Django appRelated
- DisallowedHost: Invalid HTTP_HOST header — Django's 400 Bad RequestDjango received a request for a host name that is not in ALLOWED_HOSTS, so it answered 400 Bad Request. Add the domain the site is served on to ALLOWED_HOSTS, without https:// and without a port, or read the list from an environment variable, and redeploy.
- Django hosting in 2026: how to deploy a Django app, and whereFor most Django apps, a platform that deploys from Git is the right pick: Render and DigitalOcean App Platform are the simplest fixed monthly prices, Fly.io is the cheapest in dollars, Railway bills by usage, and a VPS is for when you want root. Livops fits Django apps whose users are in Uzbekistan, at 39 credits a month. Below: prices and free tiers side by side, a Django deployment checklist, and how to host a Django project on Livops.
- Gunicorn "Worker failed to boot": what it means and how to fix itGunicorn's worker could not load your application, so the master process shut down. The cause is the Python traceback printed just above the message: most often a missing package or variable, or a wrong module:variable path in the gunicorn command. Fix what the traceback names and the workers boot.
- 502 Bad Gateway after deploying: what it means and how to fix itThe proxy in front of your app reached for it and got no valid answer: nothing was listening on the port it tried, or the process closed the connection mid-request. After a deploy that is almost always one of five things: the app listens on the wrong port or on 127.0.0.1, it crashed on start, it was still starting, it ran out of memory, or the proxy points at the wrong port. The app's own log says which.