Django CSRF port wildcard

I am running a Django project in a container that defaults to expose the app on port 80, but due to specifics of my configuration that port is in use and I have it remapped to 8080. This breaks the app because the CSRF_TRUSTED_ORIGINS contains http://localhost but not http://localhost:8080. I want to allow any port from localhost, so I instead tried http://localhost:* (and also http://localhost:) but I'm getting a CSRF error with this config telling me that http://localhost:8080 isn't in the allowed host list.

I see directions for wildcard domains in the CSRF configuration directions, but nothing for wildcard ports. How can I accept any requests from localhost, regardless of port?

Django's CSRF_TRUSTED_ORIGINS (introduced with stricter Origin header checking in Django 4.0+) does not support wildcard ports like http://localhost:* or http://localhost:. The matching logic expects full origins (scheme + host, optionally with port if non-standard). Subdomain wildcards (*.example.com) work, but ports do not.

In your settings.py:

import os

# Base trusted origins
CSRF_TRUSTED_ORIGINS = [
    "http://localhost",
    "http://127.0.0.1",
    # Add your specific mapped port
    "http://localhost:8080",
    "http://127.0.0.1:8080",
]

# Optional: Make it dynamic for different environments / ports
# (highly recommended for Docker/dev setups)
if DEBUG:  # or based on an env var
    port = os.getenv("DJANGO_PORT", "8080")  # or whatever your container exposes
    CSRF_TRUSTED_ORIGINS.extend([
        f"http://localhost:{port}",
        f"http://127.0.0.1:{port}",
    ])

    # Also support common dev ports
    for p in ["8000", "8080", "3000", "5173"]:  # add your typical ones
        if p != port:
            CSRF_TRUSTED_ORIGINS.extend([
                f"http://localhost:{p}",
                f"http://127.0.0.1:{p}",
            ])

Also Update ALLOWED_HOSTS

ALLOWED_HOSTS = [
    "localhost",
    "127.0.0.1",
    "0.0.0.0",  # common in containers
    # Add any other hosts
]
Вернуться на верх