I have a Django project that I'd like to distribute on a public repository like bitbucket or github. I'd like it to be as easy to install as possible, so I'm including the full project, not just the pluggable apps. This means that the settings.py
file will be included as well.
How can I avoid the problem of settings.SECRET_KEY
being the same for every installation?
Is the only simple solution to have the user manually modify settings.py
?
Should I store the key in the default database and have settings.py
initialize it if it doesn't exist? That would solve the problem, but I'm wondering if there is already a standard way of doing this.
Thanks!
Generating a Django SECRET_KEY To generate a new key, we can use the get_random_secret_key() function present in django. core. management. utils .
What happens if I change Django secret key? Once you change the SECRET_KEY on production, all the old sessions and cookies are invalidated, users are logged out and data in sessions are lost. This is good if your SECRET_KEY is compromised!
The way I like to organize my Django Project is – Keeps all Django apps in apps folder, static files (scripts, js, CSS) in the static folder, HTML files in templates folder and images and media content in the media folder.
To add to what Carles Barrobés said, you can generate a new key using the method that Django uses in startproject
:
from django.utils.crypto import get_random_string chars = 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)' get_random_string(50, chars)
For Django 1.10 and above, the above code snippet is nicely wrapped up in a function.
from django.core.management.utils import get_random_secret_key get_random_secret_key()
Link to GitHub repo
I'd go about it this way:
Have the secret key in a separate file "secret_key.py". This file does not exist for a pristine installation. In your settings.py include something like:
try: from .secret_key import SECRET_KEY except ImportError: SETTINGS_DIR = os.path.abspath(os.path.dirname(__file__)) generate_secret_key(os.path.join(SETTINGS_DIR, 'secret_key.py')) from .secret_key import SECRET_KEY
The function generate_secret_key(filename)
that you will write generates a file called filename
(which, as we call it, will be secret_key.py
in the same dir as settings.py
) with the contents:
SECRET_KEY = '....random string....'
Where random string is the generated key based on a random number.
For key generation you can use Umang's suggestion https://stackoverflow.com/a/16630719/166761.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With