Chapter 15 · 10 min read
Settings, Security and Deployment
Settings, Security and Deployment
Your blog works on your laptop. Before real visitors arrive, several settings must change, because Django's development defaults are unsafe on purpose. This chapter explains what to change and why, and gives you the overall shape of a production setup.
What you will learn
- What
settings.pycontains and which settings are dangerous to leave alone. - How to keep secrets out of your code with environment variables.
- How to run Django's deployment check and collect static files.
- The security protections Django gives you, and what remains your job.
- The overall shape of a production deployment.
Settings are plain Python
config/settings.py is a normal Python file, so you can compute values, read environment variables and import modules. The ones to know:
| Setting | Purpose | Development | Production |
|---|---|---|---|
SECRET_KEY | Signs cookies and tokens | Any value | Long random secret, never committed |
DEBUG | Show detailed error pages | True | False |
ALLOWED_HOSTS | Hostnames the site may serve | Empty is fine with DEBUG on | Your domain names |
DATABASES | Database connection | SQLite | Usually PostgreSQL |
STATIC_ROOT | Where collectstatic collects files | Not needed | A folder served by the web server |
MAILERS | Email backends (Django 6.1) | Console backend | A real backend, such as SMTP |
What Django protects you from
- XSS: templates escape variables automatically.
- CSRF: POST forms need a token, checked by middleware.
- SQL injection: the ORM passes values as parameters, never pastes them into SQL.
- Clickjacking: middleware sets headers that stop other sites from framing yours.
- Weak passwords: passwords are hashed, and validators reject weak ones.
Your job is not to turn these off. Never use safe on user text, never write raw SQL with string formatting, and never commit secrets.
Step by step
1. Read secrets and switches from environment variables
Edit config/settings.py. Add import os near the top and change these settings:
import os
SECRET_KEY = os.environ.get("DJANGO_SECRET_KEY", "dev-only-insecure-key")
DEBUG = os.environ.get("DJANGO_DEBUG", "0") == "1"
ALLOWED_HOSTS = [h for h in os.environ.get("DJANGO_ALLOWED_HOSTS", "").split(",") if h]
STATIC_ROOT = BASE_DIR / "staticfiles"
SECURE_SSL_REDIRECT = not DEBUG
SESSION_COOKIE_SECURE = not DEBUG
CSRF_COOKIE_SECURE = not DEBUG
SECURE_HSTS_SECONDS = 0 if DEBUG else 3600
Because DEBUG now defaults to off, turn it on in the terminal you use for development.
macOS and Linux:
export DJANGO_DEBUG=1
python manage.py runserver
Windows PowerShell:
$env:DJANGO_DEBUG = "1"
python manage.py runserver
On Windows Command Prompt use set DJANGO_DEBUG=1. Create a proper secret key with:
python -c "from django.core.management.utils import get_random_secret_key; print(get_random_secret_key())"
2. Run the deployment check
Pretend to be production and ask Django to audit your settings.
macOS and Linux:
export DJANGO_DEBUG=0
export DJANGO_ALLOWED_HOSTS=example.com
python manage.py check --deploy
Windows PowerShell:
$env:DJANGO_DEBUG = "0"
$env:DJANGO_ALLOWED_HOSTS = "example.com"
python manage.py check --deploy
In a new Django 6.1 project, the generated settings contain a MAILERS entry that prints emails to the terminal. The deployment check therefore reports the error mail.E001 until you give the default mailer a production-ready backend. This is the shape Django 6.1 documents:
MAILERS = {
"default": {
"BACKEND": "django.core.mail.backends.smtp.EmailBackend",
"OPTIONS": {"host": "smtp.example.com", "use_tls": True},
},
}
MAILERS is not yet enabled by default in existing projects, and it will replace EMAIL_BACKEND and the related EMAIL_* settings in Django 7.0 (which the release notes now call Django 2028). Optional warnings about HSTS subdomains and preload may also remain; read each message and decide.
3. Collect static files and freeze dependencies
python manage.py collectstatic
python -m pip freeze > requirements.txt
collectstatic copies the static files of every installed app, including the admin's, into STATIC_ROOT.
4. The production recipe
On a Linux server or a hosting platform the usual recipe is:
- Install the packages in
requirements.txtinto a virtual environment. - Set environment variables for the secret key,
DJANGO_DEBUG, allowed hosts and the database. - Run
python manage.py migrateandpython manage.py collectstatic. - Start a production server such as
gunicorn config.wsgi, usually behind a web server or a platform's router that handles HTTPS. - Serve the static files folder. WhiteNoise (
pip install whitenoise) is a popular way to serve collected static files from the same application. - Replace SQLite with PostgreSQL by changing
DATABASES; install a driver such aspsycopg[binary].
runserver is never used in production. Gunicorn does not run on Windows, but servers are usually Linux anyway.
Content Security Policy (new in Django 6.0)
Django 6.0 added built-in Content Security Policy support: ContentSecurityPolicyMiddleware, nonces through the csp() context processor, and policies written as dictionaries in the SECURE_CSP setting. A policy tells browsers which sources of scripts and styles are trusted. Read the CSP how-to guide when you are ready for a hardening pass.
The deployment checklist
The official deployment checklist is worth reading in full. Key points:
- Keep
SECRET_KEYsecret and rotate it if it leaks. - Turn
DEBUGoff. - Set
ALLOWED_HOSTS. - Use HTTPS everywhere and secure cookies.
- Use a real database and back it up.
- Configure logging and error reporting.
- Configure email.
Check it works
- With
DJANGO_DEBUG=1the site works as before. check --deploylists what is still wrong. Only the email error (until you configure a real mailer) and optional HSTS warnings should remain.collectstaticcopies files into astaticfilesfolder.
Exercises with solutions
Exercise 1: a real secret key
Generate a key, store it in DJANGO_SECRET_KEY, and run the site again.
Solution. Run the one-line key generator above. Copy the output, then export it:
export DJANGO_SECRET_KEY='paste-the-key-here'
(On PowerShell: $env:DJANGO_SECRET_KEY = "paste-the-key-here".) Start the server with DJANGO_DEBUG=1 set. Existing sessions stop working because the signing key changed, so you must log in again. This shows why leaking or rotating the key matters.
Exercise 2: read the checklist
Compare your settings with the official deployment checklist.
Solution. Open the checklist (link below) and go through each item. Write down which ones your project already satisfies (CSRF middleware is enabled), and which you would need to do (HTTPS, database backups, logging).
Exercise 3: fix every error
Make python manage.py check --deploy report no errors.
Solution. Set DJANGO_DEBUG=0, set DJANGO_ALLOWED_HOSTS, provide a long random DJANGO_SECRET_KEY, and replace the default entry of MAILERS with the SMTP configuration shown above. Remaining warnings (such as SECURE_HSTS_INCLUDE_SUBDOMAINS) are advice you can choose to follow.
Common mistakes
- Leaving
DEBUG = Trueon a public site. Error pages leak your code and settings. - Committing
SECRET_KEYor passwords to Git. - Empty
ALLOWED_HOSTSwithDEBUGoff. Every request gets a 400 error. - Forgetting
collectstatic. The site loads with no CSS. - Forgetting to set
DJANGO_DEBUG=1in a development terminal after this chapter's change. The site redirects to HTTPS and pages stop loading. - Using SQLite and
runserverfor a busy public site.
Key takeaways
- Development defaults are unsafe on purpose; production needs
DEBUGoff, a secret key, allowed hosts and HTTPS. - Read secrets from environment variables.
python manage.py check --deployis a free security review.collectstatic, a real database and a production server complete the picture.- Django 6.1 introduces
MAILERS; the deployment check flags the development-only console backend.
Official links
- Deployment checklist: https://docs.djangoproject.com/en/6.1/howto/deployment/checklist/
- How to deploy Django: https://docs.djangoproject.com/en/6.1/howto/deployment/
- Settings reference: https://docs.djangoproject.com/en/6.1/ref/settings/
- Security in Django: https://docs.djangoproject.com/en/6.1/topics/security/
- Content Security Policy how-to: https://docs.djangoproject.com/en/6.1/howto/csp/
