improved getattr template filter

 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
@register.filter
def getattr (obj, args):
    """ Try to get an attribute from an object.

    Example: {% if block|getattr:"editable,True" %}

    Beware that the default is always a string, if you want this
    to return False, pass an empty second argument:
    {% if block|getattr:"editable," %}
    """
    splitargs = args.split(',')
    try:
      (attribute, default) = splitargs
    except ValueError:
      (attribute, default) = args, ''

    try:
      attr = obj.__getattribute__(attribute)
    except AttributeError:
      attr = obj.__dict__.get(attribute, default)
    except:
      attr = default

    if hasattr(attr, '__call__'):
        return attr.__call__()
    else:
        return attr

More like this

  1. getattr template filter by joshua 6 years, 2 months ago
  2. Flickr Sync by bretwalker 5 years, 10 months ago
  3. Wiki-like markup for sub templates by luckystarr 5 years, 8 months ago
  4. SQL Log Middleware - with multiple databases by guglielmocelata 2 years, 3 months ago
  5. Django using admin horizontal filter in forms by crodjer 1 year, 11 months ago

Comments

(Forgotten your password?)