This will raise a clear error if the variable is not set.
What is SECRET_KEY
SECRET_KEY is a random string used by Django for:
- Signing sessions and cookies
- Protecting CSRF tokens
- Generating password reset links
- django.contrib.messages
Generating a New Key
from django.core.management.utils import get_random_secret_key
print(get_random_secret_key())
Or from the command line:
python -c "from django.core.management.utils import get_random_secret_key; print(get_random_secret_key())"
Security Rules
- Never commit to git — you cannot erase git history
- Minimum length of 50 characters
- Unique per environment (dev != prod)
- Rotate immediately if compromised
Storing in an Environment Variable
# settings.py
import os
SECRET_KEY = os.environ.get('SECRET_KEY')
if not SECRET_KEY:
raise ValueError("SECRET_KEY environment variable is not set!")
.env:
SECRET_KEY=django-prod-abcdef1234567890...
.gitignore
.env
*.env
.env.local
.env.production
If the Key Is Leaked
- Generate a new key immediately
- Deploy it to production
- All active sessions will be invalidated (users will be logged out)
- CSRF tokens will become invalid
django-environ for Validation
import environ
env = environ.Env(SECRET_KEY=(str, None))
SECRET_KEY = env('SECRET_KEY')
This will raise a clear error if the variable is not set.
💬 Comments (0)
No comments yet
Be the first to share your opinion about this article!