Distributing Django projects with unique SECRET_KEYs

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.


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


Open a Django shell with python manage.py shell and do the following to create a secure random secret key in Django 2.1:

>>> from django.core.management.utils import get_random_secret_key
>>> get_random_secret_key()
'[GENERATED KEY]'
>>>

Note: The >>> represents the shell prompt, and should not be typed.

Edit: Some answers here suggest automatically generating a file with a secret key in it from within the Django settings file itself. This is unsuitable for a production environment for a couple reasons. First of all, future deployments to new machines will create mismatching keys. Secondly, you'll need to take extra care to ensure there is no read access to that file from other programs or users. For these reasons it is generally advisable and common practice to store secrets on production machines as environment variables.

Tags:

Django