When you start a django project,
django-admin startproject automatically adds a
SECRET_KEY to each new project.
However if you want to change it, or add a seperate one to each of your environment, e.g: one for ‘production’, one for ‘staging’, one for ‘production’ etc, how do you gerenerate a new ones?
There would be another case: you cloned a project from a remote repo and want to
change the default
For sure there are some other solutions but I believe that the best solution
comes from native Django itself;
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # generate_secret.py from django.core.management import utils print(utils.get_random_secret_key())
When we run above codes it returns a 50 character random string usable as a
SECRET_KEY setting value.
In the above snippet as you can see we are using get_random_secret_key function from
In addition to that if you’d like to use it as a ‘one-liner’ command run it like below:
$ python manage.py shell -c 'from django.core.management import utils; print(utils.get_random_secret_key())'
- 2021-08-11 : Update tags
- 2021-08-11 : Add in series