You put Django online and three errors show up that nearly everyone meets: DisallowedHost, CSRF verification failed and the page with no styles (static files give a 404). They have one thing in common: on your computer it worked because DEBUG was on and the address was localhost. The short answer: they are three settings.py values that have to know the real domain. To get Django running in the first place, see the base article first.
The three errors, one line each
| Error |
Cause |
Fix in settings.py |
DisallowedHost: Invalid HTTP_HOST header |
The domain you opened the site with is not in the list of allowed hosts. |
ALLOWED_HOSTS = ["asuaempresa.co.mz", "www.asuaempresa.co.mz"]. Include every name the site opens with. |
CSRF verification failed (403) when submitting a form |
Behind HTTPS, Django does not trust the form’s origin. |
CSRF_TRUSTED_ORIGINS = ["https://asuaempresa.co.mz", "https://www.asuaempresa.co.mz"]. Since Django 4.0 it must include the protocol. |
Page with no styles; files under /static/ give a 404 |
With DEBUG = False Django stops serving static files. |
Set STATIC_ROOT, run python manage.py collectstatic and serve that folder through the web server (see below). |
Static files, step by step
| 1 |
Set the two lines in settings.py:STATIC_URL = "/static/" STATIC_ROOT = BASE_DIR / "staticfiles"
|
|
| 2 |
Gather everything in one folder, inside the application’s environment: python manage.py collectstaticRepeat after every update that touches static files.
|
|
| 3 |
Make the web server serve that folder. In cPanel, the simple way is to copy (or link) the contents of staticfiles to a folder inside the domain’s public folder, at the path STATIC_URL gives. On a VPS, nginx serves it with a location /static/ block and an alias.
|
|
| 4 |
Restart the application and reload without cache (Ctrl+F5).
|
|
There is an alternative that skips step 3: the whitenoise package, which lets Django itself serve static files efficiently. Follow its documentation: you install it with pip and add it to MIDDLEWARE.
Do not fix it by leaving DEBUG = True on. With it on, any error shows visitors your paths, settings and sometimes credentials. Django requires ALLOWED_HOSTS precisely when DEBUG is off. And never use ALLOWED_HOSTS = ["*"] in production.
|
Behind an HTTPS proxy (nginx on a VPS), tell Django the original request was secure, or CSRF and redirects fail: SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https"), and only if the proxy sends that header and clears it on requests coming from outside. See gunicorn and systemd on a VPS. For passwords and the secret key: environment variables and secrets.
|
|
Adjusted settings.py and the error is still there? Send us the domain and the last lines of the application log.
Open a support ticket
|
RECOMMENDED PRODUCT Web hosting with cPanel Domain and SSL included, daily backups and the panel you already know. from 321,75 MT/mo (3-year plan, with coupon) See plans |