What Django signs with SECRET_KEY
SECRET_KEY is the HMAC key behind Django's signing framework. Anyone who knows it can create values Django will trust:
| Feature | What an attacker with the key can do |
|---|---|
| Sessions (signed cookie backend) | forge a session cookie and log in as any user |
| Password reset tokens | create valid reset links for any account |
django.core.signing / TimestampSigner | forge any signed value your code trusts |
| Messages framework (cookie storage) | inject messages |
| CSRF tokens | not directly (CSRF uses its own secret), but keep the key secret anyway |
Database-backed sessions are not forgeable with the key alone, but password reset tokens are. In practice: a leaked SECRET_KEY is an account-takeover risk and must be rotated.
Moving SECRET_KEY out of settings.py
- Generate a key above and add the single-quoted line to
.env(and.envto.gitignore). - Read it in
settings.py. With django-environ:
import environ
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent.parent
env = environ.Env()
environ.Env.read_env(BASE_DIR / ".env")
SECRET_KEY = env("SECRET_KEY") # ImproperlyConfigured if missing
SECRET_KEY_FALLBACKS = env.list("SECRET_KEY_FALLBACKS", default=[])- In production, set
SECRET_KEYas a real environment variable on the host (Heroku config vars, Render, Fly secrets, a Kubernetes Secret) instead of shipping a .env file. - Run
python manage.py check --deployto confirm Django accepts the key.
The Django .env generator builds a complete .env for Django with DEBUG, ALLOWED_HOSTS, Postgres, Redis and Celery keys around this one.
Rotating the key without logging everyone out
Django 4.1 added SECRET_KEY_FALLBACKS: new values are signed with SECRET_KEY, and values signed with any key in the fallback list are still accepted.
# 1. new key becomes SECRET_KEY, old key moves to the fallbacks SECRET_KEY='<new key>' SECRET_KEY_FALLBACKS='<old key>' # 2. after SESSION_COOKIE_AGE has passed (default 2 weeks), remove the fallback SECRET_KEY_FALLBACKS=
If the old key leaked, skip the fallback: every token signed with it must stop working now. On Django versions before 4.1 there is no fallback setting, so rotation always ends all sessions.
Other ways to generate a Django secret key
# Django itself (needs Django installed) python -c "from django.core.management.utils import get_random_secret_key; print(get_random_secret_key())" # Python standard library only python -c "import secrets; print(secrets.token_urlsafe(50))" # OpenSSL openssl rand -base64 48
All three are fine: Django only requires length and randomness, not a specific alphabet. For other frameworks, see the Rails secret key generator, the Laravel APP_KEY generator or the general secret generator.