Django: where do I call settings.configure?

RexE picture RexE · Nov 8, 2013 · Viewed 17.5k times · Source

The Django docs say that I can call settings.configure instead of having a DJANGO_SETTINGS_MODULE. I would like my website's project to do this. In what file should I put the call to settings.configure so that my settings will get configured at the right time?

Edit in response to Daniel Roseman's comment:

The reason I want to do this is that settings.configure lets you pass in the settings variables as a kwargs dict, e.g. {'INSTALLED_APPS': ..., 'TEMPLATE_DIRS': ..., ...}. This would allow my app's users to specify their settings in a dict, then pass that dict to a function in my app that augments it with certain settings necessary to make my app work, e.g. adding entries to INSTALLED_APPS.

What I envision looks like this. Let's call my app "rexe_app". In wsgi.py, my app's users would do:

import rexe_app
my_settings = {'INSTALLED_APPS': ('a','b'), ...}
updated_settings = rexe_app.augment_settings(my_settings)
# now updated_settings is {'INSTALLED_APPS': ('a','b','c'), 'SESSION_SAVE_EVERY_REQUEST': True, ...}
settings.configure(**updated_settings)

Answer

alko picture alko · Nov 8, 2013

Its not quite equivalent, since settings DJANGO_SETTINGS_MODULE updates defaults, found in django.conf.settings.global_settings, while parameter for configure completely ignores them, so you have to add some additional processing.

Beware, first, that you can't modify INSTALLED_APPS on the fly, as they are examined once on settings processing. For example, to apply modifications to INSTALLED_APPS in Apache-deployed application, you need to restart Apache.

Second, as settings are imported, therefore this point is prone to injections of some sorts, and is highly vulnerable to expose them to users.

If this is a meta app, there are two possibilities:

  1. If you want to provide default settings for `django`-wise setting, add following to `default_settings.py` in your app:
    INSTALLED_APPS = ('default_app', )
    
    Just make sure you don't import `default_settings.py` in your app, and make your users add to their settings.py
    from rexe_app.default_settings import *
    INSTALLED_APPS += ('users_app', )
    
    that effectively will set `INSTALLED_APPS` to `('default_app', 'users_app', )` for your end users.
  2. In case you need `rexe_app`-wise settings, you can default them in your app's `__init__.py`:
    from django.conf import settings
    REXE_APP_CONFIG_PARAM = getattr(settings, 'REXE_APP_CONFIG_PARAM', 
        'default_param_value')
    
    so when user needs to change default `REXE_APP_CONFIG_PARAM` he needs to just add
    INSTALLED_APPS = ('rexe_app')
    REXE_APP_CONFIG_PARAM = 'user_param_value'
    
    to his `settings.py`.