How to set Django settings from within a function?

Is there a way to set django settings from within a function?

Essentially, I want to create logic blocks that set various django settings (perhaps more than one at a time). An quick example of this:

def set_log_settings(env):
    if env == 'prod':
        set_settings({'LOG_LEVEL': 'INFO', 'LOG__HANDLER': 'prodhandler'}
    else:
        set_settings({'LOG_LEVEL': 'DEBUG', 'LOG__HANDLER': 'devhandler'}

I would call this instead of having in my settings.py:

if env == 'prod':
   LOG_LEVEL='INFO'
   LOG__HANDLER='prodhandler'
else:
   LOG_LEVEL='DEBUG'
   LOG__HANDLER'='devhandler'

Note: I want to call this from within the settings.py file, not from the actual loaded app code, it's more a question of grouping settings-related logic, rather than a question of when that logic runs. This would allow me to not have a giant settings file where all logic is sitting virtually un-organized at the global level.

Create a file like "settings_functions.py" and import it inside "settings.py".

# settings_functions.py

def set_log_settings(env):
    if env == 'prod':
        return {'LOG_LEVEL': 'INFO', 'LOG__HANDLER': 'prodhandler'}
    else:
        return {'LOG_LEVEL': 'DEBUG', 'LOG__HANDLER': 'devhandler'}

# settings.py

from . import settings_functions
log_settings = settings_functions.set_log_settings(env)

LOG_LEVEL = log_settings.get("LOG_LEVEL", "")
LOG__HANDLER = log_settings.get("LOG__HANDLER", "")
Back to Top