How to Create SECRET_KEY for Django Settings

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!

原文链接:How to Create SECRET_KEY for Django Settings

© 版权声明
THE END
喜欢就支持一下吧
点赞5 分享
Do not let dream just be your dream.
别让梦想只停留在梦里
评论 抢沙发

请登录后发表评论

    暂无评论内容