Generate a Secret Key
Use this form to generate secret keys for your next Django application and copy them to your clipboard.
How to use this secret key
Generate a key, copy it and insert it in your project’s .env file.
# Django settings
DEBUG=True
SECRET_KEY=COPY_KEY_FROM_ABOVE
ALLOWED_HOSTS=127.0.0.1,localhost
How does this secret key generator work?
It’s easier to answer this by showing you code (don’t worry, it’s really easy). I’ll start off with the code that my implementation was based off of - the Django implementation of get_random_secret_key().
Django implementation
def get_random_secret_key():
"""
Return a 50 character random string usable as a SECRET_KEY setting value.
"""
chars = "abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)"
return get_random_string(50, chars)
In other words, it takes a string of characters and passes it to get_random_string(). Then get_random_string selects 50 characters (as requested) from the string and returns it. Here is get_random_string:
def get_random_string(length, allowed_chars=RANDOM_STRING_CHARS):
"""
Return a securely generated random string.
The bit length of the returned value can be calculated with the formula:
log_2(len(allowed_chars)^length)
For example, with default `allowed_chars` (26+26+10), this gives:
* length: 12, bit length =~ 71 bits
* length: 22, bit length =~ 131 bits
"""
return "".join(secrets.choice(allowed_chars) for i in range(length))
That is the entire Django implementation. It uses the secrets module to choose a character for i in range(length) times.
Javascript implementation
function getRandomSecretKey() {
const chars = 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)';
const randomSecretKey = getRandomString(50, chars);
return randomSecretKey;
}
function getRandomString(length, characters) {
let result = '';
const charactersLength = characters.length;
for (let i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
}
So, it’s close. It uses Math.random() instead of Python’s secrets module to select characters (at something fairly to random) from the same list of characters as is in the Django implementation.
How random is it?
It’s random enough for dev, but for production I’d recommend using the Django function to generate a slightly more secure key.