Template Tag for Retrieving complex Settings

 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. View to retrieve objects meeting a complex tag query by nathangeffen 3 years, 3 months ago
  2. blocksetter by jerzyk 6 years, 4 months ago
  3. CommaSeparatedIntegerField with CheckboxSelectMultiple Widget by brendansellers 1 year, 4 months ago
  4. Custom Template Tag - No Translate by robcharlwood 4 years ago
  5. Template tag to dump database query info by pryankster 7 years ago

Comments

(Forgotten your password?)