Generate Django Secret
Generate a random 50-character Django secret key, then copy it into your project's private configuration. This online tool generates the key on our server. For production, generate it on a machine you control using the local command below, and keep the value out of Git.
Generate a key, then copy it into your environment file.
Use the key in your Django project
Set DJANGO_SECRET_KEY in your hosting provider's secret settings or your application's environment. Use a different value for development and production. In settings.py, read that variable rather than pasting the key into the file:
import os
SECRET_KEY = os.environ["DJANGO_SECRET_KEY"]
This Django 5.2 example follows the official deployment checklist, with an explicit environment-variable name. The name must match your deployment configuration. A missing variable raises KeyError; do not hide a missing production secret behind a hardcoded default.
A .env file is not loaded automatically by Django or os.environ. If you use one locally, configure a loader using our Django environment variables tutorial, and follow the Git setup guide to keep it out of version control. Restart your application after changing its environment.
Generate a secret key locally
Run this in a private terminal with Python 3.6 or later. It uses Python's cryptographically strong secrets.token_urlsafe() function and does not require Django:
python -c "import secrets; print(secrets.token_urlsafe(50))"
Here, 50 means random bytes, not output characters: this command produces 67 URL-safe characters. That differs from this site's 50-character generator; a Django secret does not have to be exactly 50 characters. Keep the output private and save it once in your secret store. Do not generate a new key every time your app starts.
Changing an existing secret key
Django uses the key for signing, including password-reset tokens and some session data; it is not a user's password. Replacing it can invalidate existing signed values. Django 4.1 and later support SECRET_KEY_FALLBACKS for a planned transition. Remove old keys after your transition window, and do not retain a compromised key as a trusted fallback.
For a new project, set the key before deployment and leave it stable across restarts. Then explore open-source Django projects to see how real applications organize their settings.
Examples checked with Django 5.2 and Python 3.11. Updated .