← Back to Django, page 4

django-0065 · Easy fresher

How should Django settings differ between development and production, and how do you read secrets from environment variables?

Keep one codebase and vary configuration through environment variables (twelve-factor style) or small per-environment settings modules. Secrets such as SECRET_KEY and database passwords never go into git. Read them with os.environ, parse booleans and lists explicitly, fail fast when a required value is missing, and set DEBUG=False in production.

Full answer

Settings that change per environment: DEBUG, ALLOWED_HOSTS, SECRET_KEY, DATABASES, cache and email backends, CSRF_TRUSTED_ORIGINS, logging, security flags.

Pattern 1, environment variables with defaults only for safe values:

python
import os
DEBUG = os.environ.get("DJANGO_DEBUG", "0") == "1"
SECRET_KEY = os.environ["DJANGO_SECRET_KEY"]          # KeyError if missing: fail fast
ALLOWED_HOSTS = os.environ.get("DJANGO_ALLOWED_HOSTS", "").split(",")

Convert types yourself: environment values are always strings, so "False" is truthy unless compared. Libraries such as django-environ or pydantic-settings add parsing, .env files for local use and database URL support.

Pattern 2, modules: settings/base.py, settings/dev.py (imports base, overrides), settings/prod.py, selected with DJANGO_SETTINGS_MODULE. Easy to read, but the prod file is still configured from the environment for secrets.

Rules:

  • A dev-only default for SECRET_KEY is acceptable; production must not start without a real one.
  • .env files are for local development, ignored by git, and never shipped in images.
  • Never set DEBUG=True in production: it leaks settings and tracebacks and keeps all SQL in memory.
  • Run python manage.py check --deploy against the production settings.
  • Empty string ALLOWED_HOSTS.split(",") gives [""]; filter out blanks.
  • Rotate secrets by supporting SECRET_KEY_FALLBACKS (Django 4.1+).
python
import os

os.environ.update({"DJANGO_DEBUG": "False", "DJANGO_SECRET_KEY": "k" * 60,
                   "DJANGO_ALLOWED_HOSTS": "schoolabe.com, www.schoolabe.com,", "DATABASE_PATH": ":memory:"})


def env_bool(name, default=False):
    raw = os.environ.get(name)
    return default if raw is None else raw.strip().lower() in {"1", "true", "yes", "on"}


def env_list(name):
    return [item.strip() for item in os.environ.get(name, "").split(",") if item.strip()]


def require(name):
    try:
        return os.environ[name]
    except KeyError:
        raise RuntimeError(f"Missing required environment variable {name}") from None


import django
from django.conf import settings

settings.configure(
    DEBUG=env_bool("DJANGO_DEBUG"),
    SECRET_KEY=require("DJANGO_SECRET_KEY"),
    ALLOWED_HOSTS=env_list("DJANGO_ALLOWED_HOSTS"),
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": os.environ["DATABASE_PATH"]}},
)
django.setup()

print(settings.DEBUG, settings.ALLOWED_HOSTS)
print(bool(os.environ["DJANGO_DEBUG"]), "<- a non-empty string is truthy, so parse it")
print(len(settings.SECRET_KEY))

del os.environ["DJANGO_SECRET_KEY"]
try:
    require("DJANGO_SECRET_KEY")
except RuntimeError as exc:
    print(exc)

Standalone script. It sets the variables itself so it runs anywhere; in production they come from the process environment or a secret manager. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): False ['schoolabe.com', 'www.schoolabe.com'] True <- a non-empty string is truthy, so parse it 60 Missing required environment variable DJANGO_SECRET_KEY

Key points

  • Environment variables are strings; parse them explicitly
  • Fail fast on missing secrets
  • Never commit secrets or .env files
  • check --deploy against production settings
  • SECRET_KEY_FALLBACKS supports key rotation

Common mistakes

  • Using bool(os.environ['DEBUG']) and getting True for 'False'
  • Committing .env or a real SECRET_KEY
  • Leaving DEBUG=True in production
  • Giving ALLOWED_HOSTS a blank entry from an empty variable

Follow-ups

  • How would you rotate SECRET_KEY without logging everyone out?
  • How do you keep secrets out of Docker images?
  • When is a settings package better than environment variables?

Tips

  • Mention fail-fast on missing secrets
  • Call out string-to-bool parsing
  • Name check --deploy