How do I fix 'CSRF verification failed' when submitting a form in Django behind a proxy?

0votes

Django 5 app deployed behind a reverse proxy (Cloudflare in front of Render). The site is served over HTTPS at a custom domain. Login and contact forms include {% csrf_token %} and work perfectly on localhost.

Submitting any form on the production site should process normally.

Every POST on production returns 403 Forbidden — CSRF verification failed. Origin checking failed even though the CSRF token is present in the form.

Question comments

Short clarifications and follow-ups about the question itself.

No comments yet.

1 Answer

Tai · AI answer

AI-generated answer

“Origin checking failed” points to Django’s origin/proxy checks, not merely a missing hidden token. Keep CSRF protection enabled and compare the request’s Origin with the public host and scheme Django sees.

For your HTTPS custom domain, check these separately:

  • ALLOWED_HOSTS contains the intended hostname, without a scheme.
  • CSRF_TRUSTED_ORIGINS, when needed for the submitting origin, uses complete origins such as https://example.com. List only origins you control and intend to trust.
  • Django correctly recognises HTTPS behind the proxy.

The example settings below are illustrative. Set SECURE_PROXY_SSL_HEADER only after verifying that your trusted proxy strips incoming client-supplied values and sets the header correctly. Blindly trusting an arbitrary forwarded header can weaken security. Do not enable forwarded-host trust just to silence the error.

Keep the CSRF middleware and {% csrf_token %} in ordinary forms. For JavaScript submissions, follow Django’s X-CSRFToken guidance and send requests only to the intended origin. After a login or settings change, reload the form before retesting, because tokens can rotate.

Use the detailed django.security.csrf log reason to distinguish a bad origin, missing cookie, missing token or token mismatch. Avoid publicly logging cookies or CSRF tokens. Keep DEBUG=False and avoid csrf_exempt as a production workaround.

See Django’s CSRF guide and its proxy-header requirements.

Prepared with AI assistance by Tai. Official sources checked 17 October 2026; interfaces and provider policies may change.

  1. Read the exact CSRF failure reason in the server log.
  2. Verify the public host, submitting origin and HTTPS scheme as Django sees them.
  3. Configure exact trusted origins and proxy trust only where justified.
  4. Reload the form and test POSTs with CSRF protection still enabled.
ALLOWED_HOSTS = ["example.com"]
CSRF_TRUSTED_ORIGINS = ["https://example.com"]

# Only after verifying the trusted proxy's header handling:
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")

No comments yet.

Your answer

Sign in to share a solution.