This free Django secret key generator is an online tool that lets you generate a unique, secure SECRET_KEY for your project in seconds. Pick a character set, copy the result into your server configuration, and keep it out of Git so your production site stays protected.
Django Secret Key Generator: How to Use It
Press generate and the page builds a new key in your browser, so the value is created client-side and never travels to a server. A copy button then places the key on your clipboard. Because the characters come from a cryptographically secure source, the default 50 characters are unpredictable, which is the same standard that the built-in Django SECRET_KEY generator follows when you run startproject. Use this Django secret key generator once per environment, then store the output privately.
- Create a key, copy it, and paste it straight into your host's variable panel under the name
DJANGO_SECRET_KEY. - Redeploy the app so the new value is picked up at startup.
- Open the site, log in and submit a form to confirm that sessions and forms still work.
- Close the generator tab; the key lives only in the page until you leave it.
Choose the key length and character set
Django expects a long value, and 50 characters is the usual minimum. Every extra character adds entropy, while the symbol pool decides how much each position contributes. The default pool mixes lowercase letters, digits and special characters; hosts that choke on punctuation can switch to an alphanumeric pool instead.
| Key length | Default pool (50 symbols) | Alphanumeric pool (62 symbols) |
|---|---|---|
| 50 chars | 282.2 bits | 297.7 bits |
| 64 chars | 361.2 bits | 381.1 bits |
| 80 chars | 451.5 bits | 476.3 bits |
| 100 chars | 564.4 bits | 595.4 bits |
Check the entropy of a generated key
Each position in the default pool carries about 5.64 bits, so a 50-character key holds roughly 282 bits of entropy. Even at a trillion guesses per second, that outlasts the age of the universe many times over. The realistic security risks are leaks and reuse, not brute force, so treat the key like a private credential and never reuse one across projects.
What a Django SECRET_KEY Does
Django treats the setting as a core security measure, a cryptographic secret for anything it needs to trust later. It is not encryption and it is not a user's password. It signs values so the framework can detect tampering: Anyone issuing credentials to client applications can use the api key generator to create long random strings with a custom prefix.
- Session cookies that keep users logged in
- CSRF tokens on every form
- Password reset links and other one-time tokens
- Anything passed through
django.core.signing
Whoever holds the key can create values that Django accepts as genuine.
Django also audits the value for you. Running django-admin check --deploy warns when the key is shorter than fifty characters, has fewer than five distinct characters, or still begins with the django-insecure- prefix that new projects get. Those warnings are a quick signal that a placeholder slipped into your live settings.
What happens if SECRET_KEY is exposed
Attackers with the key can forge session cookies, impersonate users, produce valid password reset links and tamper with signed data. A compromised key is a serious security incident, since every signed value is suspect, so replace it immediately and review recent account activity.
Store the Random String in Environment Variables
Never hardcode the key in a file you commit. Keep this random string in an environment file or your host's secrets manager, add that file to .gitignore, and use separate values for development, staging and production. Anything in version control can leak, and Git history keeps it forever, even after you delete the line. Set the value in your hosting dashboard before each deployment, and skip the one that startproject wrote into the template. In a fresh PHP framework project, the laravel app key generator outputs a random 32-byte base64 value with the prefix Laravel expects in its env file.
Reading the key in settings.py
Read the SECRET_KEY value from the environment and let a missing variable raise an error instead of silently falling back to a default:
import os
SECRET_KEY = os.environ["DJANGO_SECRET_KEY"]Using python-decouple or django-environ
If you keep a local .env file, Django will not load it on its own. Libraries such as python-decouple and django-environ read it for you and can cast types, so debug flags arrive as real booleans rather than strings.
Passing the key with Docker Compose
With Docker Compose, list DJANGO_SECRET_KEY under the service's environment section, or point to an env file kept out of the repository.
Whichever route you choose, give your laptop its own throwaway SECRET_KEY, generated separately. A local copy of the live key tends to end up in screenshots, shell history and chat messages, and a separate local value costs nothing.
Rotating a Live SECRET_KEY: a Worked Walkthrough
Say a contractor's laptop was lost and a project's key sat in their shell history. The decision: replace the live key today without logging out every customer. I open this secret key generator, set the length to 72 characters and keep the default symbol pool. The math is simple: 72 × log2(50) ≈ 406.4 bits of entropy, which is 124.2 bits more than the old 50-character value's 282.2 and well above the 50-character, 5-unique-character floor that check --deploy enforces.
Next I copy the key into the host's variable panel as DJANGO_SECRET_KEY, then move the old value into SECRET_KEY_FALLBACKS. Django verifies signatures against both, so the 14-day default SESSION_COOKIE_AGE (1,209,600 seconds) is the window to watch: after 14 days every session signed with the old key has expired on its own.
| Step | Old key | New key |
|---|---|---|
| Day 0, deploy | Verifies only | Signs and verifies |
| Day 14, cleanup | Removed from fallbacks | Signs and verifies |
For a rotated SECRET_KEY, the number to watch is that 14-day window, not the key length: a 72-character key only protects you once the leaked one is gone from the fallbacks, and a stronger value does nothing for sessions that the old one can still sign for. Check the fallback list on the day you promised yourself, not whenever you remember. My judgement call is to shorten the fallback period if the leak is confirmed, accepting that some users must sign in again, because a leaked key that still verifies is a live forgery risk. One caveat: reset links signed with the old key stop working the moment it leaves the list, so a user who requested one on day 13 must request another.
Generate a Random Key in the Terminal
For production, generate the value on a machine you control. Each command prints a fresh key:
- Django's helper:
python3 -c "from django.core.management.utils import get_random_secret_key; print(get_random_secret_key())" - OpenSSL:
openssl rand -base64 50, trimmed to the characters you want - No Django needed:
python3 -c "import secrets; print(secrets.token_urlsafe(50))"
Use the Python secrets module
The secrets module needs Python 3.6 or later and does not require Django. Note that token_urlsafe(50) counts input bytes, not output characters, so it prints about 67 characters. That is fine, because Django only asks for a long, unpredictable value.
A quick sanity check after generating: the SECRET_KEY string should contain no spaces or quotes that would break a shell or a settings line. If a character does cause trouble, wrap the value in single quotes in your environment file or regenerate with a letters-and-digits pool.
Rotate Your Signing Key Safely
Swapping the SECRET_KEY will invalidate existing sessions and any outstanding signed links, so schedule the change. Django 4.1 and later supports SECRET_KEY_FALLBACKS, which lets old keys keep verifying while new ones sign; older 3.x and 2.x projects have no such list, and users simply sign in again. Follow the deployment checklist, rotate after any suspected leak, and remove a compromised value from the fallbacks.
A tidy order of operations helps: generate the replacement SECRET_KEY, add it as the new key, move the old one into the fallback list, deploy, and wait for the longest session lifetime to pass. Only then delete the old value, so nobody is logged out mid-task and no signed link goes stale unexpectedly.
Frequently Asked Questions
- Why does Django need a SECRET_KEY?
- Django uses it to sign session cookies, password reset tokens, CSRF tokens, and other security-sensitive values -- anyone who obtains it can forge these signatures and potentially hijack sessions or bypass protections. It must be kept secret and never committed to version control.
- What character set does this match?
- The same one Django's own django.core.management.utils.get_random_secret_key() draws from: lowercase and uppercase letters, digits, and the symbols !@#$%^&*(-_=+) — 76 characters total, avoiding shell-unsafe characters like quotes or backticks that could cause problems if the key is ever handled in a shell script or .env file.
- Is 50 characters long enough?
- Yes -- 50 characters from a 76-character set gives roughly 312 bits of entropy, vastly more than needed for HMAC-based signing. Django's own default generator uses exactly this length; there's no benefit to going shorter, and little practical benefit to going much longer.
- How should I store this in production?
- In an environment variable (read via os.environ['SECRET_KEY'] or a library like django-environ), a secrets manager, or your deployment platform's encrypted config -- never hardcoded in settings.py or committed to your repository.
- What happens if I rotate my SECRET_KEY?
- Every existing session, password reset link, and signed cookie becomes invalid immediately, forcing all users to log in again -- this is expected and is exactly why rotation is a legitimate response to a suspected key leak, but not something to do routinely without reason.