Generate and Store a Django SECRET_KEY Securely

Create a strong key locally, keep it out of source control, and rotate it promptly if exposed.

What Django's SECRET_KEY does

Django uses SECRET_KEY to sign data for features such as sessions, messages, and password-reset tokens. Keep the production key random and secret; anyone who obtains it may be able to forge data signed with that key.

Generate a key locally

Run this in the Python environment where Django is installed:

python -c "from django.core.management.utils import get_random_secret_key; print(get_random_secret_key())"

Store it outside source control

Put the generated value in your hosting secret store or a protected environment file, keep that file out of Git, and load it from the environment in Django settings:

import os

SECRET_KEY = os.environ["DJANGO_SECRET_KEY"]

If the key is exposed

Treat it as compromised and replace it in every environment that uses it. Without a fallback, existing sessions and password-reset tokens signed with the old key will stop validating. Django 4.1 and later supports temporary rotation through SECRET_KEY_FALLBACKS, but do not keep an exposed key there; remove compromised keys from all fallbacks so signatures made with them are no longer trusted.

For an optional encrypted YAML workflow, see Secure Credentials Kit.