Login

Dynamic Django settings context processor

Author:
sciyoshi
Posted:
July 10, 2008
Language:
Python
Version:
.96
Score:
2 (after 4 ratings)

Here's a nice way of easily passing only certain settings variables to the template. Because of the way Django looks up context processors, we need a little hack with sys.modules. The blog entry is here.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# utils/context_processors.py

import sys

from django.conf import settings as django_settings

class SettingsProcessor(object):
    def __getattr__(self, attr):
        if attr == '__file__':
            # autoreload support in dev server
            return __file__
        else:
            return lambda request: {attr: getattr(django_settings, attr)}

sys.modules[__name__ + '.settings'] = SettingsProcessor()

# in settings.py

TEMPLATE_CONTEXT_PROCESSORS = (
    # ....
    'utils.context_processors.settings.GOOGLEMAPS_KEY',
    'utils.context_processors.settings.TEMPLATE_DEBUG',
    'utils.context_processors.settings.MAXMIND_URL',
)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 11 months ago

Comments

nedbatchelder (on August 17, 2012):

I'm sorry, but this seems crazy. I heard about this snippet because of a bug report that it breaks coverage.py (https://bitbucket.org/ned/coveragepy/issue/192)

Why not write a simple context processor that does what you want, like this:

# utils/context_processor.py

from django.conf import settings

def some_settings(request):
    return dict( # wrapped oddly to stay narrow
        (k, getattr(settings, k)) 
        for k in settings.SETTINGS_IN_CONTEXT
    )

# settings.py
TEMPLATE_CONTEXT_PROCESSORS = (
    # ....
    'utils.context_processors.some_settings',
}

SETTINGS_IN_CONTEXT = ['GOOGLEMAPS_KEY', 'TEMPLATE_DEBUG', 'MAXMIND_URL']

#

Please login first before commenting.