Use django-environ for Config
A snippet showing how to use django-environ to manage settings.
# Install
pip install django-environ
# settings.py
from pathlib import Path
import environ
BASE_DIR = Path(__file__).resolve().parent.parent
# Initialize env reader (with defaults & casting)
env = environ.Env(
DEBUG=(bool, False),
)
# Read from .env file at project root (optional if using real env vars)
environ.Env.read_env(BASE_DIR / ".env")
# Core flags / secrets
SECRET_KEY = env("DJANGO_SECRET_KEY")
DEBUG = env("DJANGO_DEBUG") # or env.bool("DJANGO_DEBUG", default=False)
ALLOWED_HOSTS = env.list("DJANGO_ALLOWED_HOSTS", default=["localhost", "127.0.0.1"])
# Database: supports DATABASE_URL like postgres://USER:PASS@HOST:PORT/NAME
DATABASES = {
"default": env.db(
"DATABASE_URL",
default="postgres://app:[email protected]:5432/app",
)
}
# Email (example)
EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"
EMAIL_HOST = env("EMAIL_HOST", default="smtp.sendgrid.net")
EMAIL_HOST_USER = env("EMAIL_HOST_USER", default="apikey")
EMAIL_HOST_PASSWORD = env("EMAIL_HOST_PASSWORD", default="")
EMAIL_PORT = env.int("EMAIL_PORT", default=587)
EMAIL_USE_TLS = env.bool("EMAIL_USE_TLS", default=True)
# Security examples
SECURE_SSL_REDIRECT = env.bool("DJANGO_SECURE_SSL_REDIRECT", default=not DEBUG)
SESSION_COOKIE_SECURE = env.bool("DJANGO_SESSION_COOKIE_SECURE", default=not DEBUG)
CSRF_COOKIE_SECURE = env.bool("DJANGO_CSRF_COOKIE_SECURE", default=not DEBUG)
# .env (example)
DJANGO_SECRET_KEY=super-secret-key
DJANGO_DEBUG=0
DJANGO_ALLOWED_HOSTS=example.com,www.example.com
# DATABASE_URL supports many schemes:
# Postgres: postgres://USER:PASS@HOST:PORT/NAME
DATABASE_URL=postgres://app:[email protected]:5432/app
# Email
EMAIL_HOST=smtp.sendgrid.net
EMAIL_HOST_USER=apikey
EMAIL_HOST_PASSWORD=SG.xxxxxx
EMAIL_PORT=587
EMAIL_USE_TLS=1
# Security
DJANGO_SECURE_SSL_REDIRECT=1
DJANGO_SESSION_COOKIE_SECURE=1
DJANGO_CSRF_COOKIE_SECURE=1
# Result
- Cleaner settings: types and defaults handled by django-environ.
- Easy switching between local .env and real environment variables.
- DATABASE_URL parsing removes repetitive DB config.
Explanation:
-
env.bool,env.int, andenv.listprovide safe casting with defaults. -
Centralize secrets in
.envfor local dev; in production, prefer real environment variables. -
env.db("DATABASE_URL")parses DSNs for Postgres/MySQL/SQLite automatically. -
Avoid committing
.env; add it to.gitignore.
- Category Deployment & Settings
- Total Views 651
- Last Modified 26 December, 2025
- Tags #settings #environment #django-environ #config
Previous snippet
Static and Media Settings
Next snippet