Environment Variables

Keep secrets out of your code with environment variables.

Never hard-code secrets like the SECRET_KEY, API keys or database passwords. Read them from environment variables instead, so the same code runs safely in every environment.

Tools like python-decouple or django-environ make this convenient and can read from a .env file.

Example

Example · python
import os

# Read with a safe default for local dev
SECRET_KEY = os.environ.get("DJANGO_SECRET_KEY", "dev-only-key")
DEBUG = os.environ.get("DJANGO_DEBUG", "False") == "True"

# Using django-environ:
# import environ
# env = environ.Env()
# env.read_env()
# SECRET_KEY = env("DJANGO_SECRET_KEY")

When to use it

  • A developer uses python-decouple to read DATABASE_URL and SECRET_KEY from a .env file without hardcoding secrets.
  • A DevOps engineer sets DJANGO_SETTINGS_MODULE as a container environment variable to select the production config.
  • A team uses django-environ to parse a single DATABASE_URL string into the full DATABASES dictionary automatically.

More examples

Load .env with python-decouple

Reads typed settings from a .env file using python-decouple, with sensible defaults for optional values.

Example · python
# pip install python-decouple
from decouple import config

SECRET_KEY = config("SECRET_KEY")
DEBUG = config("DEBUG", default=False, cast=bool)
ALLOWED_HOSTS = config("ALLOWED_HOSTS", cast=lambda v: v.split(","))

.env file example

Shows a typical .env file with the key variables needed for Django in production.

Example · bash
# .env (never commit this file)
SECRET_KEY=replace-me-with-50-random-chars
DEBUG=False
ALLOWED_HOSTS=mysite.com,www.mysite.com
DATABASE_URL=postgres://user:pass@localhost/mydb

Parse DATABASE_URL with dj-database-url

Converts a DATABASE_URL connection string into Django's DATABASES dict format in one line.

Example · python
# pip install dj-database-url
import dj_database_url
from decouple import config

DATABASES = {
    "default": dj_database_url.parse(config("DATABASE_URL"))
}

Discussion

  • Be the first to comment on this lesson.