DEV Community

Cover image for Django Secret Key
Rob McBryde
Rob McBryde

Posted on

Django Secret Key

When you start a new Django project, your settings.py file contains a 'SECRET_KEY' entry by default.

Both the comments and the secret key values itself both indicate that this is insecure and should not be exposed.

The SECRET_KEY' is a random 50-character string generated each time startproject is run. It is used to provide cryptographic signing in our project.

When working on a Django project that you intend to place into a production environment, you should move this secret key into a .env file.

I have used the environs package to manage my environment variables, which I have previously written about.

Creating an .env file

Create a file named .env in the root directory of your project and in it paste in your secret key from your settings.py file:

SECRET_KEY=django-insecure-egyi&vxcm6kkpkaa&wnw0+&ps6%4-s@&c=+891+jfu8j5*adz4
Enter fullscreen mode Exit fullscreen mode

Note there are no spaces in the .env file

Now update your settings.py file to read your secret key from your environment variable:

# settings.py file
SECRET_KEY = env.str("SECRET_KEY")
Enter fullscreen mode Exit fullscreen mode

Regenerating your secret key

Even though our SECRET_KEY is out of our settings.py file we potentially aren't safe yet. If you have made any Git commits before doing this change, our secret key is stored in our Git history. Anyone who can access out source code and Git history can see it.

The solution is to create a new SECRET_KEY and add it to our .env file. First ensure that you have created a .gitignore file in the root directory of your project and add a .env entry to it so that Git will not track it.

In order to generate a new SECRET_KEY is by invoking Python's built-in secrets module by running the following from your terminal:

python3 -c "import secrets; print(secrets.token_urlsafe())"
Enter fullscreen mode Exit fullscreen mode

Now paste this new randomly generated secret into your .env file overwriting the SECRET_KEY entry. Ensure that there are no quotes (" or ') surrounding your pasted key and that there are no spaces between the equals sign and your key in the .env file.

Now you have a more secure secret key!

Top comments (0)