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
If somehow the
SECRET_KEY is exposed, it needs to be generated again. In this shot, let's learn how to generate a Django
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
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())
get_random_secret_key()function to generate a secret key and print the generated key to the console.
SECRET_KEYusing 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())'
Run the command given above in the terminal below. The output will be a
SECRET_KEY consisting of 50 characters.
And, that's it! We can now use the generated value as our
View all Courses