Settings, Deployment and Testing

Settings, Deployment and Testing in Django: In the rehearsal room a show runs with every convenience switched on.

The Analogy: A Theatre Moving a Show From Dress Rehearsal to Opening Night

In the rehearsal room a show runs with every convenience switched on. The house lights are up full so the director can see the actors' faces, the safety curtain is tied back out of the way, loose script pages are taped to the scenery where anyone can read them, and the stage manager calls the cues aloud so the cast can learn them. Every one of these is exactly right for a rehearsal. Not one of them is safe to keep when a paying audience walks through the door.

Opening night flips a specific set of switches. The house lights go down, the fire systems and the safety curtain are armed, the taped-up script pages are struck from the set, and the master keys that were sitting on the props table go into the locked office safe. Each switch is small on its own, and each one left in the rehearsal position is its own kind of incident: a lit auditorium destroys the illusion, an un-armed safety curtain is a genuine hazard, and a script page taped to the flats tells the front row every plot twist before the actor speaks it.

The stage manager does not trust memory for any of this. There is a written pre-show checklist, run the same way every night, and it is the list rather than anyone's recollection that catches the one switch someone forgot. The rehearsals themselves happen in an empty house: a full run of the entire show, every cue and light and entrance, that can go wrong in any way at all without a single paying patron being affected, because nothing that happens in that empty room ever reaches a real audience. And the two configurations are written down separately. The intimate rehearsal-room setup and the full mainstage setup live on their own pages, not as one master switch a nervous stagehand flips halfway through the run.

The failure mode is opening the doors with the checklist skipped. The work lights are still up, the script pages are still taped to the flats, and the office safe is standing open exactly where the rehearsal left it. Nobody sabotaged anything. Every switch was simply left in the position that was correct yesterday, in the rehearsal room, for an audience of no one. The first paying patron to glance at the set reads tomorrow's ending straight off a taped page, and the master keys are there for the taking.


Syntax or Core Structure

A Django project is configured entirely by module-level names in a settings file. The dangerous defaults are the convenient ones, so the first rule is that secrets come from the environment and the process refuses to boot without them, while diagnostic switches default to their safe (off) position.

import os
from django.core.exceptions import ImproperlyConfigured


def required_env(name):
    # Fail loudly at boot if a required secret is absent.
    try:
        return os.environ[name]
    except KeyError:
        raise ImproperlyConfigured("Missing required environment variable: " + name)


SECRET_KEY = required_env("DJANGO_SECRET_KEY")
DEBUG = os.environ.get("DJANGO_DEBUG", "false").lower() == "true"

We can reduce that policy to a runnable plain-Python stand-in. It reads settings from an in-memory dict standing in for the process environment, treats the secret as required, and defaults DEBUG to off. In real Django the missing-secret case raises and the process never starts; here we return an explicit error marker so the REPL can print the outcome instead of a traceback.

def get_setting(env, name, default=None, required=False):
    if name in env:
        return env[name]
    if required:
        return "ERROR missing " + name
    return default


def load(env):
    secret = get_setting(env, "SECRET_KEY", required=True)
    if secret.startswith("ERROR"):
        return secret
    debug = env.get("DEBUG", "false").lower() == "true"
    return "loaded secret=" + secret + " debug=" + str(debug)


dev_env = {"SECRET_KEY": "dev-xyz", "DEBUG": "true"}
prod_env = {"SECRET_KEY": "prod-abc"}
broken_env = {"DEBUG": "true"}

print(load(dev_env))
print(load(prod_env))
print(load(broken_env))

Output:

loaded secret=dev-xyz debug=True
loaded secret=prod-abc debug=False
ERROR missing SECRET_KEY

The development environment supplies both names and turns DEBUG on. Production supplies only the secret, so DEBUG falls back to its safe default of off. The broken environment forgot the secret entirely, and instead of booting with a blank or hard-coded key it stops with a named error. A settings file that hard-codes a fallback secret "just so it runs" has quietly turned that failure into a silent, forgeable-session success.


Technical Depth: Config Switches, a Deploy Check, and Test Isolation

The settings that separate development from production

A handful of settings are the entire difference between a safe deployment and an incident. Each is harmless at its development value and dangerous at that same value in production.

SettingDev valueProd valueRisk if left at the dev value
DEBUGTrueFalseError pages leak source, settings, and SQL
ALLOWED_HOSTSany hostexplicit listHost-header poisoning of password-reset links
SESSION_COOKIE_SECUREFalseTrueSession cookie sent in cleartext over HTTP
SECURE_SSL_REDIRECTFalseTrueRequests answered without TLS
SECRET_KEY sourceinline defaultrequired env varA committed key forges sessions and signed tokens

A deploy check catches the switch you forgot

Django ships a manage.py check --deploy command that inspects the live settings and reports every switch left in an unsafe position. The value is that it is a list, run mechanically, not a human trying to remember eight things at once. The stand-in below scans a settings dict and returns one finding per problem.

def check_deploy(cfg):
    findings = []
    if cfg.get("DEBUG"):
        findings.append("DEBUG is True")
    if cfg.get("ALLOWED_HOSTS") == ["*"]:
        findings.append("ALLOWED_HOSTS allows any host")
    if not cfg.get("SESSION_COOKIE_SECURE"):
        findings.append("SESSION_COOKIE_SECURE is False")
    if not cfg.get("SECRET_KEY"):
        findings.append("SECRET_KEY is empty")
    return findings


prod = {"DEBUG": False, "ALLOWED_HOSTS": ["shop.example.com"],
        "SESSION_COOKIE_SECURE": True, "SECRET_KEY": "prod-abc"}
sloppy = {"DEBUG": True, "ALLOWED_HOSTS": ["*"],
          "SESSION_COOKIE_SECURE": False, "SECRET_KEY": ""}

print("prod findings: " + str(len(check_deploy(prod))))
for f in check_deploy(sloppy):
    print("sloppy: " + f)
print("sloppy findings: " + str(len(check_deploy(sloppy))))

Output:

prod findings: 0
sloppy: DEBUG is True
sloppy: ALLOWED_HOSTS allows any host
sloppy: SESSION_COOKIE_SECURE is False
sloppy: SECRET_KEY is empty
sloppy findings: 4

The production configuration produces zero findings; the sloppy one produces four, one per switch left at its development value. This is the checklist from the analogy: a lit auditorium (DEBUG), an unlocked stage door (ALLOWED_HOSTS), a cookie sent in the clear, and a safe left open. None of them is subtle once something reads them off mechanically.

Settings belong in per-environment modules

The two configurations should not be one file with if DEBUG: branches threaded through it. The durable structure is a base.py holding everything common, a dev.py that imports from base and turns the conveniences on, and a prod.py that imports from base and reads every secret from the environment. The process chooses one with DJANGO_SETTINGS_MODULE, so there is never a moment where a single flag toggles a live service between the two. Serving is the same discipline: gunicorn config.wsgi runs the app behind a real WSGI server, manage.py collectstatic gathers assets so the app server never has to, and neither step reads a value that was not set deliberately for that environment.


Real World Example: A Test Suite That Proves Isolation and Bounds Queries

Deployment safety is only credible if a test suite defends it, and the two properties that matter most are the ones beginners skip: every test starts from an identical, isolated database, and the query count of a hot path stays bounded. Django's TestCase wraps each test in a transaction and rolls it back afterward, so a row one test inserts is gone before the next test runs; assertNumQueries fails the test if a view runs more queries than expected. The program below models both against an in-memory database.

SEED = [
    {"id": 1, "name": "Hammer", "active": True},
    {"id": 2, "name": "Old", "active": False},
]


class DB:
    def __init__(self, rows):
        self.rows = [dict(r) for r in rows]
        self.queries = 0

    def active(self):
        self.queries = self.queries + 1
        return [r for r in self.rows if r["active"]]

    def add(self, row):
        self.rows.append(row)


def fresh():
    # Each test gets a brand-new copy, like a rolled-back transaction.
    return DB(SEED)


def test_list_shows_active_only():
    db = fresh()
    names = [r["name"] for r in db.active()]
    return "Hammer" in names and "Old" not in names


def test_query_count_bounded():
    db = fresh()
    before = db.queries
    db.active()
    return db.queries - before == 1


def test_add_is_isolated():
    db = fresh()
    db.add({"id": 3, "name": "Leak", "active": True})
    return len(db.rows) == 3


def test_isolation_held():
    db = fresh()
    return len(db.rows) == 2


TESTS = [
    ("list_shows_active_only", test_list_shows_active_only),
    ("query_count_bounded", test_query_count_bounded),
    ("add_is_isolated", test_add_is_isolated),
    ("isolation_held", test_isolation_held),
]
passed = 0
for name, fn in TESTS:
    ok = fn()
    if ok:
        passed = passed + 1
    print(name.ljust(22) + " " + ("PASS" if ok else "FAIL"))
print("passed: " + str(passed) + "/" + str(len(TESTS)))

Output:

list_shows_active_only PASS
query_count_bounded    PASS
add_is_isolated        PASS
isolation_held         PASS
passed: 4/4

Each test calls fresh(), which hands back a brand-new DB built from the same seed, so nothing one test does can reach another. The first test asserts the list view shows the active row and hides the inactive one. The second records the query counter, calls active() once, and asserts the counter advanced by exactly one, the bounded-query check that catches an N+1 regression. The third inserts a third row and asserts the database now holds three. The fourth, running immediately after, asserts the database holds only two.

That fourth assertion is the whole point. The third test added a row and passed; the fourth still sees two rows, which proves the insertion never leaked out of the test that made it. All four report PASS and the suite prints passed: 4/4. The bounded-query test and the isolation test together are what let a deployment change with confidence: the settings can be tightened, the code refactored, and the suite still holds the line on both correctness and query budget.

The design gets the important shape right. Isolation comes from constructing fresh state per test rather than sharing one mutable object, which is exactly what a per-test transaction rollback buys you. The query counter, crude as it is, encodes the single most valuable performance assertion a test can make: not "how fast" but "how many round trips."

The flaws are real. fresh() copies each row with dict(r), a shallow copy, so a nested value inside a row would still be shared across tests and could leak in a way this suite would never catch. The query counter only counts calls to active(), so it models assertNumQueries for reads and is blind to writes entirely. Every test here exercises the happy path; not one drives the 403 and 404 branches where real incidents live, so a permission regression would sail through green. And the runner has no failure isolation of its own: a test that raised, rather than returning False, would abort the whole run instead of being reported as a single FAIL the way a real test runner would.


Common Mistakes

  1. Committing the secret key or leaving a hard-coded fallback in settings. A SECRET_KEY in the repository can forge session cookies and password-reset tokens for everyone. A SECRET_KEY = os.environ.get("KEY", "insecure-default") is worse than no default, because the app boots happily on the default and nobody notices until the signatures are already broken.
  2. Shipping with DEBUG = True. The debug error page prints your source, your settings (including database credentials), and the failing SQL to anyone who can trigger an exception. It is a full information-disclosure vulnerability, not a convenience.
  3. Setting ALLOWED_HOSTS = ["*"] to silence a DisallowedHost error. The setting exists to pin the Host header; a wildcard lets an attacker set it to their own domain and poison the absolute URLs Django builds, most damagingly in password-reset emails.
  4. Forgetting the transport-security switches. SESSION_COOKIE_SECURE, CSRF_COOKIE_SECURE, SECURE_SSL_REDIRECT, and an HSTS header are each off by default. Left off, the session cookie rides over plain HTTP and a single insecure request hands it to a network eavesdropper.
  5. Branching one settings file on if DEBUG: instead of separate modules. Threading environment logic through a single file means one wrong flag flips a live service into development mode. Separate dev.py and prod.py modules make the choice explicit and reviewable.
  6. Logging request bodies, headers, or whole settings objects. A logger that dumps the POST body captures passwords; one that logs the settings module captures the secret key. Secrets belong in the environment and must never be written to a log line, which is far more widely readable than the process memory it came from.
  7. Never running manage.py check --deploy. Django will list every unsafe setting for you, but only if you ask. Skipping it in CI is choosing to find out about the lit auditorium from a paying patron instead of from the checklist.
  8. Running the test suite against the development or production database. Tests must run against a separate, disposable test database that Django creates and destroys. Point them at a real database and they either corrupt data or, worse, pass because of rows a fresh database would not contain.
  9. Writing only happy-path tests. A suite that never asserts the 401, 403, and 404 responses will stay green while an authorization regression ships. The tests that matter most are the ones that prove access is denied.

Best Practices

  • Read every secret from the environment and refuse to boot without it. A small required_env helper that raises ImproperlyConfigured turns a missing secret into an immediate, obvious failure instead of a silent insecure default.
  • Default every diagnostic and security switch to its safe position. DEBUG off, SESSION_COOKIE_SECURE and CSRF_COOKIE_SECURE on, SECURE_SSL_REDIRECT on, HSTS set. The convenient value should be the one you opt into for development, never the default.
  • Split settings into base, dev, and prod modules selected by DJANGO_SETTINGS_MODULE. Shared configuration lives in base; each environment imports it and overrides only what differs, so the difference between them is small and reviewable.
  • Run manage.py check --deploy in CI and treat any finding as a build failure. The checklist is only useful if it runs mechanically on every change, not when someone happens to remember it.
  • Serve behind a real server and pre-gather static files. Run the app under gunicorn or an ASGI server, put static assets behind collectstatic and a web server or CDN, and never rely on the development server or DEBUG-mode static serving in production.
  • Isolate every test and assert query counts on hot paths. Let TestCase wrap each test in a rolled-back transaction, and wrap the important views in assertNumQueries so an N+1 regression fails the build instead of slowing production.
  • Test the denial paths explicitly. Assert the 401, 403, and 404 responses for unauthenticated, unauthorized, and scoped-out requests, because those are the branches an attacker exercises and the ones a refactor silently breaks.
  • Keep secrets out of logs and error reports. Scrub request bodies, filter sensitive settings from error reports with Django's sensitive-variable decorators, and never log a whole settings object.

Practice Exercises

  1. Harden required_env. Extend it to also reject a value that is present but empty, and to accept a cast argument so DJANGO_DEBUG can be parsed to a real boolean at the boundary rather than compared as a string every time. Confirm that a blank secret now fails as loudly as a missing one.
  2. Grow the deploy check. Add findings to check_deploy for SECURE_SSL_REDIRECT being off and for a SECRET_KEY shorter than a safe length, then run it against both the prod and sloppy dicts and confirm the counts change as you expect.
  3. Prove the isolation is real. Add a test that inserts two rows and a following test that asserts the seed count, then deliberately break isolation by having fresh() return one shared module-level DB instead of a new one, and watch which test starts failing and why.
  4. Cover a denial path. Add a role field to the seed rows and a visible_to(db, role) method, then write tests asserting that an "admin" role sees the inactive row while a "guest" role receives an empty list, so the suite fails the moment the authorization rule regresses.