Have you ever pushed to the repository a Django project with SECRET_KEY
? Ups, it happens to me very often. Don’t worry. This can be easily fixed.
The SECRET_KEY
is used in Django for cryptographic signing. It is used to generate tokens and hashes. If somebody will have your SECRET_KEY
he can recreate your tokens.
Storing SECRET_KEY
in the repository code is not secure. It should be removed from the code and loaded from environment variables (or some configuration). You can use for example python-decouple to separate configuration variables from the code.
Once SECRET_KEY
was committed into the code repository, it needs to be generated again. Luckily, we can use Django get_random_secret_key()
function to generate new SECRET_KEY
.
from django.core.management.utils import get_random_secret_key
# print new random secret key
print(get_random_secret_key())
This code can be run in the terminal as a command:
python -c 'from django.core.management.utils import get_random_secret_key; \
print(get_random_secret_key())'
If you have new SECRET_KEY
then you can use python-decouple
.
# in your settings.py file
from decouple import config
SECRET_KEY = config("SECRET_KEY")
The SECRET_KEY
can be then set as environment variable or can be saved in .env
file (which is not tracked in the code repository).
Let's stay in touch!
Would you like to be notified about new posts? Please fill this form.