Login

Template Tag for Retrieving complex Settings

Author:
joelbitar
Posted:
February 7, 2011
Language:
Python
Version:
1.2
Score:
0 (after 0 ratings)

Very much like the snippet joshua wrote (http://djangosnippets.org/snippets/67/) for the same purpose but with the addition that this lets the user get values for more complex settings like dicts and lists

 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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
from django import template
from django.conf import settings
register = template.Library()

"""
Usage:

{% setting DEBUG %}
or
{% setting DATABASES.default.NAME %} # Get the name of the database
or
{% setting INSTALLED_APPS.2 %}  #get the third installed app.
or
{% setting DEBUG %}
"""

@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:
            setting = settings
            # Enables param to tag to be for example "DATABASES.default.ENGINE"
            for name in self.option.split('.'):
                # if is an int. get from the setting by index.
                if name.isdigit():
                    setting = setting[int(name)]
                else:
                    if type(setting) == dict:
                        setting = setting.get(name)
                    else:
                        setting = setting.__getattr__(name)
            
            return str(setting)
        except:
            return ""

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 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

Please login first before commenting.