Expose filtered settings to templates request context

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# in context_processor.py

import settings

def settings_context(request):
    """Exposes somewhat filtered project settings in a `project_settings` key 
    of the request context, so you can use stuff like this in templates:
    
    {% if project_settings.DEBUG and project_settings.GOOGLE_MAP_API_KEY %}
        <p>Dude, Google API key is {{ project_settings.GOOGLE_MAP_API_KEY }}.</p>
    {% endif %}
    """
    _settings = {}
    for setting in dir(settings):
        if setting.startswith('__'):
            continue
        try:
            setting_value = getattr(settings, setting)
            if type(setting_value) in [bool, str, int, float, tuple, list, dict]:
                _settings[setting] = setting_value
        except:
            pass
    return {'project_settings': _settings}

# in settings.py

TEMPLATE_CONTEXT_PROCESSORS = (
    # ...
    'myapp.context_processors.settings_context',
    # ...
)

More like this

  1. testdata tag for templates by showell 4 years, 11 months ago
  2. LinkShare Pixel Tracking template tag for Satchmo by maxk 3 years, 3 months ago
  3. FirstRun Middleware by TheMysteriousX 2 years, 11 months ago
  4. Mobile browser detection middleware by pavl 3 years, 11 months ago
  5. Partial JSON template rendering by barbuza 6 years, 5 months ago

Comments

cricogik (on December 23, 2010):

django.conf only wraps projects settings, so You can do it in simpler way:

def settings_context(request):
    from django.conf import settings
    return {
        'project_settings': settings.__dict__.get('_wrapped').__dict__.copy()
    }

regards.

#

n1k0 (on December 30, 2010):

Sure, this is by far better, thanks!

#

(Forgotten your password?)