Login

getattr template filter

Author:
joshua
Posted:
February 27, 2007
Language:
Python
Version:
Pre .96
Score:
2 (after 2 ratings)

Put inside mysite/templatetags/getattr.py Add mysite to your INSTALLED_APPS

In your template:

{% load getattr %}
{{ myobject|getattr:"theattr,default value" }}

Thanks to pterk for optimizations! \o/

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

@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," %}
    """
    (attribute, default) = args.split(',')
    try:
        return obj.__getattribute__(attribute)
    except AttributeError:
         return  obj.__dict__.get(attribute, default)
    except:
        return default

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

RichardBronosky (on July 24, 2007):

I needed to pass the attribute name as a variable, not a string. So, to make this kind of usage work:

{% field in field_order %}{{ object_list|getattr:field }}, {% endfor %}

I replaced line 14 with:

args = args.split(',')
if len(args) == 1:
    (attribute, default) = [args[0], ''] 
else:
    (attribute, default) = args

I actually wrote my own filter to do this. Then, when I came to post it, I found that this one existed and included a nifty default value. I decided to merge them.

WRoks for me.

#

Please login first before commenting.