TExcelTAD
Home › Django › Django Settings & Deployment

Django Settings & Deployment

On your laptop, runserver with DEBUG = True is perfect. On the internet it would be dangerous: debug pages leak your code and settings, and the development server isn't built for real traffic. Deployment means running the same project with production settings behind a proper application server. This lesson covers the settings that change, the commands you run, and a typical server setup.

Settings that differ in production

Setting Development Production
DEBUG True False — never True in production
SECRET_KEY anything long, random, secret — read from the environment
ALLOWED_HOSTS [] (localhost allowed when DEBUG) your domain names, e.g. ["bookshelf.example.com"]
DATABASES SQLite file usually PostgreSQL or MySQL
STATIC_ROOT not needed folder that collectstatic fills
SECURE_SSL_REDIRECT, SESSION_COOKIE_SECURE, CSRF_COOKIE_SECURE False True (HTTPS only)
SECURE_HSTS_SECONDS 0 e.g. 31536000 once HTTPS works
logging / error reporting console log files, email to ADMINS, or a service like Sentry

Reading settings from the environment

Secrets and per-server values don't belong in version control. Read them from environment variables in settings.py, with safe defaults:

python
# mysite/settings.py
import os
from pathlib import Path

BASE_DIR = Path(__file__).resolve().parent.parent

SECRET_KEY = os.environ["DJANGO_SECRET_KEY"]                 # fail loudly if missing
DEBUG = os.environ.get("DJANGO_DEBUG", "") == "1"
ALLOWED_HOSTS = os.environ.get("DJANGO_ALLOWED_HOSTS", "localhost").split(",")

The same idea in the playground — settings.configure() fed from a dictionary of environment variables:

python · try it yourself
import django
from django.conf import settings

env = {                                              # what the server would export
    "DJANGO_SECRET_KEY": "x9$k2!p0-very-long-unguessable-string-from-a-vault",
    "DJANGO_DEBUG": "0",
    "DJANGO_ALLOWED_HOSTS": "bookshelf.example.com,www.bookshelf.example.com",
}

settings.configure(
    SECRET_KEY=env["DJANGO_SECRET_KEY"],
    DEBUG=env.get("DJANGO_DEBUG", "") == "1",
    ALLOWED_HOSTS=env.get("DJANGO_ALLOWED_HOSTS", "localhost").split(","),
)
django.setup()

print("DEBUG:", settings.DEBUG)
print("ALLOWED_HOSTS:", settings.ALLOWED_HOSTS)
print("key length:", len(settings.SECRET_KEY))
DEBUG: False
ALLOWED_HOSTS: ['bookshelf.example.com', 'www.bookshelf.example.com']
key length: 50

Generate a strong key with Django's helper:

python · try it yourself
from django.core.management.utils import get_random_secret_key
key = get_random_secret_key()
print(len(key), "characters - copy it into your server's environment, never into git")
50 characters - copy it into your server's environment, never into git

ALLOWED_HOSTS in action

With DEBUG = False, Django refuses requests whose Host header isn't listed — this blocks Host header attacks (e.g. poisoned password-reset links). The test client lets us send different hosts:

python · try it yourself
import sys, types, django
from django.conf import settings
sys.modules["urls"] = urls = types.ModuleType("urls")
settings.configure(SECRET_KEY="demo", ROOT_URLCONF="urls", DEBUG=False,
                   ALLOWED_HOSTS=["bookshelf.example.com", ".example.org"])
django.setup()
from django.http import HttpResponse
from django.urls import path
from django.test import Client

urls.urlpatterns = [path("", lambda request: HttpResponse(f"served for {request.get_host()}"))]

c = Client()
for host in ["bookshelf.example.com", "shop.example.org", "evil.test"]:
    r = c.get("/", headers={"Host": host})
    print(f"{host:<22} {r.status_code} {r.content.decode() if r.status_code == 200 else ''}")
bookshelf.example.com  200 served for bookshelf.example.com
shop.example.org       200 served for shop.example.org
evil.test              400 

A leading dot (.example.org) allows the domain and all its subdomains.

The deployment checklist

Django can audit your settings for you:

bash · try it yourself
python manage.py check --deploy
System check identified some issues:

WARNINGS:
?: (security.W004) You have not set a value for the SECURE_HSTS_SECONDS setting. If your entire site is served only over SSL, you may want to consider setting a value and enabling HTTP Strict Transport Security. Be sure to read the documentation first; enabling HSTS carelessly can cause serious, irreversible problems.
?: (security.W008) Your SECURE_SSL_REDIRECT setting is not set to True. Unless your site should be available over both SSL and non-SSL connections, you may want to either set this setting True or configure a load balancer or reverse-proxy server to redirect all connections to HTTPS.
?: (security.W012) SESSION_COOKIE_SECURE is not set to True. Using a secure-only session cookie makes it more difficult for network traffic sniffers to hijack user sessions.
?: (security.W016) You have 'django.middleware.csrf.CsrfViewMiddleware' in your MIDDLEWARE, but you have not set CSRF_COOKIE_SECURE to True. Using a secure-only CSRF cookie makes it more difficult for network traffic sniffers to steal the CSRF token.

System check identified 4 issues (0 silenced).

Fix each warning (or consciously silence it) before going live.

Deploying step by step

A classic Linux server setup: nginx in front (HTTPS, static files) → gunicorn (WSGI application server running several Django worker processes) → PostgreSQL.

text
Browser ──HTTPS──▶ nginx ──┬── /static/  → files in STATIC_ROOT
                           └── everything else → gunicorn (127.0.0.1:8000) → Django

On the server, after pulling the code and activating the virtual environment:

bash · try it yourself
pip install -r requirements.txt gunicorn
python manage.py migrate --noinput
python manage.py collectstatic --noinput
gunicorn mysite.wsgi:application --bind 127.0.0.1:8000 --workers 3
Successfully installed gunicorn-23.0.0
Operations to perform:
  Apply all migrations: admin, auth, books, contenttypes, sessions
Running migrations:
  Applying books.0003_book_isbn... OK

142 static files copied to '/srv/bookshelf/staticfiles'.
[2026-10-16 09:00:00 +0000] [4120] [INFO] Starting gunicorn 23.0.0
[2026-10-16 09:00:00 +0000] [4120] [INFO] Listening at: http://127.0.0.1:8000 (4120)
[2026-10-16 09:00:00 +0000] [4120] [INFO] Using worker: sync
[2026-10-16 09:00:00 +0000] [4121] [INFO] Booting worker with pid: 4121
[2026-10-16 09:00:00 +0000] [4122] [INFO] Booting worker with pid: 4122
[2026-10-16 09:00:00 +0000] [4123] [INFO] Booting worker with pid: 4123

In practice, a process manager such as systemd (or a container platform) keeps gunicorn running and restarts it on failure. For async features (WebSockets, async def views at scale) use an ASGI server such as uvicorn with mysite.asgi:application instead.

Hosting style Examples You manage
Platform-as-a-Service Render, Railway, Fly.io, Heroku, PythonAnywhere almost nothing — push code, set env vars
Containers Docker on any cloud the image and its configuration
Virtual server a VPS with nginx + gunicorn + PostgreSQL everything, including updates and backups

Tip: Automate deployments (a script or CI pipeline that runs tests, migrate, collectstatic and restarts the server), back up the database regularly, and keep Django updated — security releases arrive several times a year.

Test yourself

Why must DEBUG be False in production?

  1. It makes pages load faster only
  2. Debug error pages expose code, settings and data to visitors
  3. Static files stop working
  4. Migrations require it

What happens with DEBUG = False when a request's Host isn't in ALLOWED_HOSTS?

  1. It is served normally
  2. Django returns 400 Bad Request
  3. Django redirects to the first host
  4. The server crashes

What is gunicorn's role in a typical deployment?

  1. Database server
  2. WSGI application server that runs Django workers
  3. Static file compressor
  4. Template engine