Django .env Generator
Django projects traditionally used settings.py for config, but that pattern leaks secrets into git. This generator produces a .env compatible with python-dotenv or django-environ — with Postgres, Redis, Celery, and SMTP already structured.
DEBUG=True SECRET_KEY=Pn8ahI81IB99woVzEzvL7FvlIeFT4YmtlcggOy4t321eoYL7Is83JzqiVEqSa8Ao ALLOWED_HOSTS=localhost,127.0.0.1 DATABASE_URL=postgres://user:password@localhost:5432/mydb REDIS_URL=redis://localhost:6379/0 CELERY_BROKER_URL=redis://localhost:6379/1 EMAIL_HOST_USER= EMAIL_HOST_PASSWORD=
Secrets regenerate on every page load. Want to combine stacks? Use the full generator.
How to use this .env in Django
- 1.Save the output as .env in your project root (next to manage.py).
- 2.Install python-dotenv: pip install python-dotenv.
- 3.Load it at the top of settings.py: load_dotenv() after importing.
- 4.Read with os.environ["KEY"] or os.getenv("KEY", "default").
Gotchas
- ⚠Read env vars at module-load time in settings.py — not inside functions — to fail fast.
- ⚠SECRET_KEY must stay secret even in dev. Generate a new one per environment.
- ⚠ALLOWED_HOSTS is comma-separated in .env, but must be a Python list in settings.py.
Common keys explained
DEBUGNever True in production. Leaks stack traces and settings.
SECRET_KEYDjango's signing key. Rotate per environment.
ALLOWED_HOSTSComma-separated domains. Required when DEBUG=False.
DATABASE_URLPostgres connection string, parsed by dj-database-url.
REDIS_URLRedis for cache + sessions.
CELERY_BROKER_URLCelery task queue backend (often the same Redis).
Loading and validating the .env in Django
# pip install django-environ
import environ
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent.parent
env = environ.Env(DEBUG=(bool, False))
environ.Env.read_env(BASE_DIR / ".env")
SECRET_KEY = env("SECRET_KEY") # raises ImproperlyConfigured if missing
DEBUG = env("DEBUG") # "True"/"False" -> bool
ALLOWED_HOSTS = env.list("ALLOWED_HOSTS", default=[])
DATABASES = {"default": env.db("DATABASE_URL")}
CACHES = {"default": env.cache("REDIS_URL")}
CELERY_BROKER_URL = env("CELERY_BROKER_URL")Django: env vars in development, staging and production
Django settings are plain Python, so every value from .env arrives as a string. DEBUG="False" is a non-empty string and therefore truthy. Always cast through django-environ or python-decouple instead of reading os.environ directly.
In production set DEBUG=False, list your real domain in ALLOWED_HOSTS, and use a SECRET_KEY that differs from development. Rotating SECRET_KEY logs every user out and invalidates password reset links. SECRET_KEY_FALLBACKS (Django 4.1+) lets you rotate without that.
Django: .env errors and fixes
django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty.The .env was not read. Check the path passed to read_env: it is relative to settings.py's BASE_DIR, not to where you run manage.py.
DisallowedHost: Invalid HTTP_HOST headerThe domain is not in ALLOWED_HOSTS. Use a comma-separated list in .env (example.com,www.example.com) and parse it with env.list().
Celery: Cannot connect to redis://localhost:6379Inside Docker Compose, localhost is the container itself. Use the service name: redis://redis:6379/1.
Django .env FAQ
django-environ or python-decouple?
django-environ understands URLs (env.db(), env.cache(), env.email()) and saves boilerplate in Django projects. python-decouple is smaller and framework-agnostic. Both read .env and cast types.
How do I generate a Django SECRET_KEY?
Use the generator above, our Django secret key generator, or python -c "from django.core.management.utils import get_random_secret_key; print(get_random_secret_key())".
Should DEBUG ever be True in production?
No. With DEBUG=True Django shows full tracebacks, local variables and settings to anyone who triggers an error.