When you start a django project, django-admin startproject
automatically adds a randomly-generated 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 SECRET_KEY
.
For sure there are some other solutions but I believe that the best solution comes from native Django itself; get_random_secret_key
:
<span>#!/usr/bin/env python3 # -*- coding: utf-8 -*- # generate_secret.py </span><span>from</span> <span>django.core.management</span> <span>import</span> <span>utils</span><span>print</span><span>(</span><span>utils</span><span>.</span><span>get_random_secret_key</span><span>())</span><span>#!/usr/bin/env python3 # -*- coding: utf-8 -*- # generate_secret.py </span><span>from</span> <span>django.core.management</span> <span>import</span> <span>utils</span> <span>print</span><span>(</span><span>utils</span><span>.</span><span>get_random_secret_key</span><span>())</span>#!/usr/bin/env python3 # -*- coding: utf-8 -*- # generate_secret.py from django.core.management import utils print(utils.get_random_secret_key())
Enter fullscreen mode Exit fullscreen mode
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 django’s utils
module.
In addition to that if you’d like to use it as a ‘one-liner’ command run it like below:
<span>$ </span>python manage.py shell <span>-c</span> <span>'from django.core.management import utils; print(utils.get_random_secret_key())'</span><span>$ </span>python manage.py shell <span>-c</span> <span>'from django.core.management import utils; print(utils.get_random_secret_key())'</span>$ python manage.py shell -c 'from django.core.management import utils; print(utils.get_random_secret_key())'
Enter fullscreen mode Exit fullscreen mode
All done!
暂无评论内容