alt-text

Generate a Random Secret Key in Django

The SECRET_KEY is an important part of our Django applications. A major use of this secret key is to provide cryptographic signing for things like session cookies, password reset tokens, and cross-site request forgery (CSRF) tokens. A strong SECRET_KEY helps ensure that tokens cannot be easily forged by attackers.

When a Django project is first created the SECRET_KEY is generated by default and can by found in settings.py. But there are many reasons you might want to generate a new or additional secret keys. Fortunately Django has a built-in support for generating random secret keys.

Let's look at an example using the Django shell. First let's start the Django shell in our project directory where manage.py resides.

python manage.py shell

Next we can use the get_random_secret_key() function to generate a new random key.

from django.core.management.utils import get_random_secret_key

get_random_secret_key()

Super easy! Each execution of get_random_secret_key() will generate a different secret key so it can easily be used to generate any number of random secret keys.