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 t
If you create a new project using template, like django-admin.py startproject --template=path_to_template project_name just put {{ secret_key }} into your project template settings file (e.g. settings.py) like SECRET_KEY = '{{ secret_key }}' and Django will generate it for you.
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 found this block of code on pypi.org which almost works like Umang's answer.
Right in your project directory run
python manage.py generate_secret_key [--replace] [secretkey.txt]
This will generate a new file secretkey.txt containing a random Django secret key. In your production settings file go and replace the secret key with the generated key.
Or in order to avoid hard coding the secret key. Add the following code snippet so that when you always run the program a new secret key will generate an updated key for you.
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Use a separate file for the secret key
with open(os.path.join(BASE_DIR, 'secretkey.txt')) as f:
SECRET_KEY = f.read().strip()
# Use a separate file for the secret key
with open('/path/to/the/secretkey.txt') as f:
SECRET_KEY = f.read().strip()
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.