Login

Template Tag for Retrieving Settings

Author:
joshua
Posted:
March 1, 2007
Language:
Python
Version:
Pre .96
Score:
6 (after 6 ratings)

Useage: {% load setting %} {% setting DEBUG %} or... {% setting MEDIA_ROOT %}

You get the gist.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
from django import template
from django.conf import settings
register = template.Library()

@register.tag
def setting ( parser, token ): 
    try:
        tag_name, option = token.split_contents()
    except ValueError:
        raise template.TemplateSyntaxError, "%r tag requires a single argument" % token.contents[0]
    return SettingNode( option )

class SettingNode ( template.Node ): 
    def __init__ ( self, option ): 
        self.option = option

    def render ( self, context ): 
        # if FAILURE then FAIL silently
        try:
            return str(settings.__getattr__(self.option))
        except:
            return ""

More like this

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

Comments

wiz (on March 1, 2007):

"be generic" (c)

@register.simpletag
def setting(name):
    return str(settings.__getattr__(name))

#

whiskybar (on March 2, 2007):

In fact, I want settings so often that I put that into context:

settings.py

....
TEMPLATE_CONTEXT_PROCESSORS = (
    'django.core.context_processors.debug', #and other common context_processors
    'yourapp.context_processors.settings', 
)

context_processors.py

from django.conf import settings as _settings

def settings(request):
    return {'settings': _settings}

#

grimboy (on March 6, 2007):

from django.conf import settings register = template.Library()

@register.simpletag
def setting(name):
    import pprint
    pp = pprint.PrettyPrinter(indent=4)
    return "<pre>%s</pre>" % (pp.pformat(settings.__getattr__(name)),)

#

graham (on August 20, 2009):

The decorator is missing an underscore:

@register.simple_tag

#

graham (on August 20, 2009):

In your template, the key name must be quoted:

{% setting 'DEBUG' %}

#

Please login first before commenting.