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 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 file:

Enter fullscreen mode Exit fullscreen mode

Note there are no spaces in the .env file

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

# file
Enter fullscreen mode Exit fullscreen mode

Regenerating your secret key

Even though our SECRET_KEY is out of our 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)