How to generate a Django SECRET_KEY

Overview

In Django, a SECRET_KEY is used for cryptographic signing, that is, to generate hashes and tokens. If any other person has access to our SECRET_KEY, then they can generate our hashes and tokens. Thus, it's very important for us to protect the SECRET_KEY.

If somehow the SECRET_KEY is exposed, it needs to be generated again. In this shot, let's learn how to generate a Django SECRET_KEY.

Generating a Django SECRET_KEY

To generate a new key, we can use the get_random_secret_key() function present in django.core.management.utils. This function returns a 50 character string that consists of random characters. This string can be used as a SECRET_KEY.

Let's see an example of this function in the following code snippet:

# importing the function from utils
from django.core.management.utils import get_random_secret_key
# generating and printing the SECRET_KEY
print(get_random_secret_key())

Explanation

  • Line 2: We import the get_random_secret_key() function from django.core.management.utils.
  • Line 5: We use the get_random_secret_key() function to generate a secret key and print the generated key to the console.

Generating a SECRET_KEY using the terminal

We can also generate a SECRET_KEY using the terminal by running the following command:

python3 -c 'from django.core.management.utils import get_random_secret_key; print(get_random_secret_key())'

Example

Run the command given above in the terminal below. The output will be a SECRET_KEY consisting of 50 characters.

Terminal 1
Terminal
Loading...

And, that's it! We can now use the generated value as our SECRET_KEY.

Free Resources