On some occasions, there might be a need to generate a random Secret key for your Django project.
The easiest option could be starting a django shell and running the below command -
from django.core.management.utils import get_random_secret_key
get_random_secret_key()
However, this may not be safe to use in a production environment.
A better option is to use a defined a set of allowed characters including upper case letters and then use Django to generate a long key.
Here is an example of it -
a. Define a list of allowed characters
lower_plus_numbers = (list(chr(o) for o in range(0x61, 0x7B))
+ list(chr(o) for o in range(0x30, 0x3A)))
punctuation = list('!@#$%^&*(-_=+)')
upper_alpha = list(chr(o) for o in range(0x41, 0x5B))
b. Generate Secret Key
from django.utils.crypto import get_random_string
key_length = 60
get_random_string(
key_length,
allowed_chars=lower_plus_numbers + punctuation + upper_alpha,
)
c. Sample Output
'*6u(3GyO&9RSO9S4%4+bX0bAN0T6!)ULrHs4XLnm@tq2!Wj!LYlS=i1vB%pl'
Comments