Login

Expose filtered settings to templates request context

Author:
n1k0
Posted:
December 21, 2010
Language:
Python
Version:
1.2
Tags:
templates settings python context_processor
Score:
1 (after 1 ratings)

Warning: I'm quite sure this is not a best practice, but this snippet has proven being very useful to me. Handle with care. I also wonder about the impact on performance, while I didn't notice any slowdown on a very small app of mine.

Idea is to expose project settings to template request context through a context processor, and _doc_ should be self-explanatory.

Of course, if you know a better way to achieve the purpose, please tell in the comments.

 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 6 years, 2 months ago
  2. LinkShare Pixel Tracking template tag for Satchmo by maxk 4 years, 5 months ago
  3. FirstRun Middleware by TheMysteriousX 4 years, 1 month ago
  4. Mobile browser detection middleware by pavl 5 years, 2 months ago
  5. Partial JSON template rendering by barbuza 7 years, 8 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!

#

Please login first before commenting.