Generate A Django Secret Key

Generate a 50-char random string, adequate for Django's `SECRETKEY` - generatedjangosecretkey.py. Skip to content. All gists Back to GitHub. Sign in Sign up.

How is storing the secret key in a file any more secure than storing it directly in settings.py? If he can read settings.py, he probably can read djangosecretkey.txt. If the attacker has compromised your machine, can't they simply load the python interpreter with settings.py to print settings.SECRETKEY? Finally, would it be a bad practice. Generate SECRET KEY. Download files. Download the file for your platform. If you're not sure which to choose, learn more about installing packages. Oct 23, 2019  Generate Django secret key commandline. GitHub Gist: instantly share code, notes, and snippets. A Django application with a command to generate a Django secret key - 1.0.2 - a Python package on PyPI - Libraries.io.

commandline.txt
$ python -c 'import random; print '.join([random.choice('abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)') for i in range(50)])'

commented Aug 22, 2018

For Python 3, this should work:

python -c 'import random; result = '.join([random.choice('abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)') for i in range(50)]); print(result)'

commented Jun 2, 2019

commented Jun 3, 2019

For Python 3, this should work:

python -c 'import random; result = '.join([random.choice('abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)') for i in range(50)]); print(result)'

I think you should use parenthesis while using print method in Python 3
python -c 'import random; print('.join([random.choice('abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)') for i in range(50)]))'

Generate A Django Secret Key

commented Oct 13, 2019

Seems exceedingly unlikely the random package contains a sufficiently secure random.

In Linux you can read from /dev/urandom or /dev/random(slower) and see someone suggesting random.SystemRandom which is probably more portable.

commented Feb 27, 2020
edited

Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Simple Django application that adds a new command:

This will generate a new file secretkey.txt containing a random Django secretkey. In your production settings file, replace the hardcoded key by:

You can avoid hardcoding the path of the key by using:

Generate A Django Secret Key

Install

You can install this package from PyPi: /pgp-public-private-key-generator.html.

Then you will need to add it to the Django's INSTALLED_APPS setting:

Generate A Django Secret Key Card

You can now use

Totp Base32 Secrets

Run this command once in your local environment, and every time you deploy your app (on the remote host), to make sure the file exists.