Is there a function for generating settings.SECRET_KEY in django?

Indeed, you can use the same function that generates a new key when you call startproject, which is django.core.management.utils.get_random_secret_key().

Note however it's not very different from your version.


I would like to add that as per the commit Fixed #31757 -- Adjusted system check for SECRET_KEY to warn about autogenerated default keys, the method get_random_secret_key() is considred to be insecure.

If you are using python 3.6+ then you can use the secrets.token_hex([nbytes=None]) function

python3 -c 'import secrets; print(secrets.token_hex(100))'

credit TLDR: Generate Django Secret Key


Note that this may not be safe to use for production, as S Ghosh is pointing out in a post below. But copy and paste this after running django-admin shell for example to quickly get a key.

from django.core.management.utils import get_random_secret_key  
get_random_secret_key()

Run this command below on the Terminal.

$ python -c 'from django.core.management.utils import get_random_secret_key; print(get_random_secret_key())'

output:

2x$e%!k_u_0*gq0s4!_u(2(^lpy&gir0hg)q&5nurj0-sseuav