Distributing Django projects with unique SECRET_KEYs
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.