Settings & Environment Variables (Django)

Managing Django settings across environments means keeping secrets and per-environment values out of settings.py and loading them from environment variables instead. This keeps DEBUG, SECRET_KEY, and database credentials safe and flexible.

Django

Hard-coding secrets in settings.py is a security risk and makes the same code hard to run in dev, staging, and production. The standard practice is to read sensitive and environment-specific values from environment variables, using os.environ or a helper like django-environ or python-decouple that can also parse types and read a .env file.

Common values pulled from the environment are SECRET_KEY, DEBUG, ALLOWED_HOSTS, and DATABASES (often from a single DATABASE_URL string). A .env file holds these locally and is git-ignored, while the real values are set in the deployment platform's environment.

Projects also split settings into modules (base.py plus dev.py and prod.py) selected via DJANGO_SETTINGS_MODULE. The two approaches combine: a shared base reads from the environment, and thin per-environment files set the few differences. Never commit production secrets to source control.

Syntax

SECRET_KEY = os.environ["DJANGO_SECRET_KEY"]

Examples

Python

import os

SECRET_KEY = os.environ["DJANGO_SECRET_KEY"]
DEBUG = os.environ.get("DJANGO_DEBUG", "0") == "1"
ALLOWED_HOSTS = os.environ.get("ALLOWED_HOSTS", "").split(",")
# with django-environ:
# DATABASES = {"default": env.db("DATABASE_URL")}

Learn it in a lesson

See also

Back to the Dictionary