Settings & Security
The settings that make development easy are dangerous on a live website. Before going public, you need to switch off debug mode, keep secrets out of your code, restrict which domains your site answers to and turn on HTTPS protections. This page shows how to prepare the Campus Events project safely.
Why development settings are unsafe
startproject creates settings for your own laptop: DEBUG = True, a SECRET_KEY written directly in settings.py and an empty ALLOWED_HOSTS. That's convenient while learning, but on the internet:
- DEBUG = True shows anyone who triggers an error your source code, file paths, installed apps, many settings and the SQL that ran. It also makes Django keep every query in memory.
- A leaked SECRET_KEY lets attackers forge signed data such as session cookies and password-reset links.
- An open host list exposes you to "Host header" attacks.
Read settings from environment variables
An environment variable is a named value set outside your code, by your terminal or hosting provider. Reading secrets from them means the same settings.py can be committed to GitHub safely and used on your laptop and your server.
campus/settings.py
import os
from pathlib import Path
from django.core.exceptions import ImproperlyConfigured
BASE_DIR = Path(__file__).resolve().parent.parent
DEBUG = os.environ.get("DJANGO_DEBUG", "") == "1"
SECRET_KEY = os.environ.get("DJANGO_SECRET_KEY")
if not SECRET_KEY:
if DEBUG:
SECRET_KEY = "django-insecure-local-development-only"
else:
raise ImproperlyConfigured("Set the DJANGO_SECRET_KEY environment variable.")
ALLOWED_HOSTS = os.environ.get("DJANGO_ALLOWED_HOSTS", "127.0.0.1,localhost").split(",")
How this behaves:
- Safe default:
DEBUGisFalseunless you deliberately setDJANGO_DEBUG=1. Forgetting a variable makes the site more secure, not less. - Fails loudly: in production, a missing secret key stops the site from starting with a clear message instead of silently using a weak key.
- Flexible hosts:
DJANGO_ALLOWED_HOSTStakes a comma-separated list such ascampus-events.example.com,www.campus-events.example.com.
To work locally with debug mode on, set the variable in your terminal before running the server:
# Windows PowerShell $env:DJANGO_DEBUG = "1" # Windows Command Prompt set DJANGO_DEBUG=1 # macOS / Linux export DJANGO_DEBUG=1 python manage.py runserver
Variables set this way last until you close the terminal. Many developers keep them in a .env file loaded by the python-dotenv package; if you do, add .env to .gitignore.
Generating a strong SECRET_KEY
Never reuse the development key in production. Django can generate a new random one:
python -c "from django.core.management.utils import get_random_secret_key; print(get_random_secret_key())"
Your key will be different every time; that's the point. Paste it into your host's environment variable settings, not into your code. If a key is ever committed to a public repository, generate a new one: changing it logs everyone out, but that's far better than leaving it exposed.
ALLOWED_HOSTS
When DEBUG is False, Django only answers requests whose Host header matches ALLOWED_HOSTS. Others get 400 Bad Request. If the list is empty, runserver refuses to start:
A leading dot matches a domain and all its subdomains: ".example.com" covers example.com and www.example.com. Avoid "*", which allows any host and defeats the purpose.
HTTPS and cookie settings
Every live site should use HTTPS. Most hosts provide a free certificate. Once your site is on HTTPS, add these settings, ideally only when DEBUG is off:
campus/settings.py
if not DEBUG:
SECURE_SSL_REDIRECT = True # send http:// visitors to https://
SESSION_COOKIE_SECURE = True # only send the login cookie over HTTPS
CSRF_COOKIE_SECURE = True # only send the CSRF cookie over HTTPS
SECURE_HSTS_SECONDS = 3600 # tell browsers "HTTPS only" for one hour; raise later
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")
SECURE_PROXY_SSL_HEADERis needed when your app runs behind a proxy that handles HTTPS for you, which is the case on most platforms such as Render. Only set it if your host's documentation says the proxy sends this header; otherwiseSECURE_SSL_REDIRECTcan cause an endless redirect loop.- HSTS makes browsers refuse plain HTTP for your domain. Start with a small value and increase it (for example to 31536000, one year) once everything works.
- If forms fail after deploying with "CSRF verification failed ... Origin checking failed", add your full address to
CSRF_TRUSTED_ORIGINS, e.g.["https://campus-events.example.com"].
Let Django check your settings
Django has a built-in deployment checklist. Run it with your production environment variables set:
python manage.py check --deploy
Before adding the HTTPS settings above, you'd see warnings like these (messages shortened):
Work through each warning until the list is empty or you understand why one doesn't apply. Read the official deployment checklist in the Django docs as well.
Other production essentials
- Database passwords belong in environment variables too, never in code.
- Custom error pages: with
DEBUG = False, Django usestemplates/404.htmlandtemplates/500.htmlif they exist. Make them friendly and on-brand. - Keep Django updated: install new 5.2.x releases promptly, since they contain security fixes.
Pushing a project to a public GitHub repository with the original SECRET_KEY and DEBUG = True still in settings.py, then deploying it unchanged. Automated bots scan GitHub for leaked secrets within minutes. Move secrets to environment variables before your first push.
Key points
- Never run a live site with
DEBUG = True. - Read
SECRET_KEY,DEBUG,ALLOWED_HOSTSand database credentials from environment variables, with safe defaults. - Set
ALLOWED_HOSTSto your real domain names. - Turn on HTTPS settings such as
SECURE_SSL_REDIRECTand secure cookies. - Run
python manage.py check --deploybefore every launch.
Tip: use the ← and → keys to move between pages.
