equivalent of getattr in a django template

2,073 views
Skip to first unread message

Chris Withers

unread,
Sep 23, 2009, 1:05:42 PM9/23/09
to django...@googlegroups.com
Hi All,

I have this view function:

def index(request,model,pk=None):

return list_detail.object_list(
request,
queryset=model.objects.all(),
paginate_by=10,
template_name='index.html',
extra_context=dict(
column_titles = [f.name for f in model._meta.fields],
)
)

Where index.html is:

<table>
<tr>
{% for title in column_titles %}
<th>{{title}}</th>
{% endfor %}
</tr>
{% for object in object_list %}
<tr>
{% for name in column_titles %}
<td>
{{*what goes here*}}
</td>
{% endfor %}
</tr>
{% endfor %}
</table>

What do I put in the marked spot to be the equivalent of
getattr(object,name)?

cheers,

Chris

--
Simplistix - Content Management, Batch Processing & Python Consulting
- http://www.simplistix.co.uk

Maksymus007

unread,
Sep 23, 2009, 1:10:21 PM9/23/09
to django...@googlegroups.com
{{object.name}} ?

Chris Withers

unread,
Sep 23, 2009, 1:13:04 PM9/23/09
to django...@googlegroups.com
Maksymus007 wrote:
> {{object.name}} ?

no, that is the equivalent of:

getattr(object,'name')

I want:

getattr(object,name)


Subtle, but rather important, difference...

Karen Tracey

unread,
Sep 23, 2009, 1:43:55 PM9/23/09
to django...@googlegroups.com

Using something like this: http://www.djangosnippets.org/snippets/38/ (with the change noted in the comment):

{{ object|gettattr:name }}

Karen

Daniel Roseman

unread,
Sep 23, 2009, 1:49:20 PM9/23/09
to Django users
It's an intentional limitation of the template language that you can't
do that. You'll need to write a custom tag or filter - luckily it can
be done very trivially as a filter:

@register.filter
def get_attr(obj, val)
return getattr(obj, val)

Now in the template:

{{ object|getattr:name }}
--
DR.

Chris Withers

unread,
Sep 23, 2009, 2:19:23 PM9/23/09
to django...@googlegroups.com
Daniel Roseman wrote:
> It's an intentional limitation of the template language that you can't
> do that. You'll need to write a custom tag or filter - luckily it can
> be done very trivially as a filter:
>
> @register.filter
> def get_attr(obj, val)
> return getattr(obj, val)
>
> Now in the template:
>
> {{ object|getattr:name }}

I agree that it doesn't belong in the template language, but it's
surprising that there's no standard filter to do this...

Is there an open issue for this or should I raise one?

Reply all
Reply to author
Forward
0 new messages