📝 Django

SECRET_KEY in Django

P
Author
Pyland
📅
Published
30.06.2026
⏱️
Reading time
1 min
👁️
Views
81
🌿
Level
Medium

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

  1. Never commit to git — you cannot erase git history
  2. Minimum length of 50 characters
  3. Unique per environment (dev != prod)
  4. 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

  1. Generate a new key immediately
  2. Deploy it to production
  3. All active sessions will be invalidated (users will be logged out)
  4. 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.

Your reaction to the article

💬 Comments (0)

🔐 Sign in to leave a comment
🚪 Login
💭

No comments yet

Be the first to share your opinion about this article!

🔗 Similar

Similar articles

Continue learning with these materials

📝

pytest-django: Testing Django

Охватываемые темы: Installation, @pytest.mark.djangodb, Fixtures, Testing views.

📅 30.06.2026 👁️ 138
📝

Django: Template Tags

Template tags are logic inside HTML. Unlike {{ variable }} which only outputs a value,...

📅 30.06.2026 👁️ 91
📝

Django: Static Files

Static files are CSS, JavaScript, images, and fonts. Django handles them in a specific way:...

📅 30.06.2026 👁️ 79

Did you like the article?

Subscribe to our updates and receive new articles first. Grow with PyLand!