pythondjangodjango-rest-framework

Can SECRET_KEY be set to get_random_secret_key() in Django settings?


I am wondering whether I can generate a random secret key inside my Django application and assign it to the SECRET_KEY variable, instead of reading it from an environment variables. e.g.

# settings.py

from django.core.management.utils import get_random_secret_key

SECRET_KEY = get_random_secret_key()

Is this recommended, or bad practice?


Solution

  • This would call get_random_secret_key() each time the settings are loaded, therefore setting a different SECRET_KEY every time, which is not good. From the docs:

    The secret key is used for:

    If you rotate your secret key, all of the above will be invalidated. Secret keys are not used for passwords of users and key rotation will not affect them.