Login

Expose filtered settings to templates request context

Author:
n1k0
Posted:
December 21, 2010
Language:
Python
Version:
1.2
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. Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 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.