get_field_display: Django needs a template filter to allow get_field_display for a dynamic field name

222 views
Skip to first unread message

Ivan Kharlamov

unread,
Sep 26, 2011, 8:01:59 AM9/26/11
to Django developers


There is often a need to write model-independent Django templates. By
now, the only field name-dependent attribute in Django templates is
get_field_display, because the particular field names must be
hardcoded for each model.

What I propose is a universal filter which should provide human-
readable value for a field of any type.

For example, like this:

<table>

{% for item in query %}

<tr>

{% for field in fields %}

<td>{{item|human_readable:field}}</td>

{% endfor %}

</tr>

{% endfor %}

<table>

I'm talking about something like this, but secure against exposing
_meta attributes:

def human_readable(value, arg):
if hasattr(value, 'get_' + str(arg) + '_display'):
return getattr(value, 'get_%s_display' % arg)()
elif hasattr(value, str(arg)):
if callable(getattr(value, str(arg))):
return getattr(value, arg)()
else:
return getattr(value, arg)
else:
try:
return value[arg]
except KeyError:
return settings.TEMPLATE_STRING_IF_INVALID

Here's the corresponding ticket: https://code.djangoproject.com/ticket/16034

Best regards,
Ivan Kharlamov

Cal Leeming [Simplicity Media Ltd]

unread,
Sep 26, 2011, 8:20:48 AM9/26/11
to django-d...@googlegroups.com
Ivan,

I completely agree that it would be useful to have something like this, as I have some up against this *exact* same problem in the past.

However, when I raised it as an issue on IRC - the only response I got was "stop putting your application logic into the templates" lol.

So, although I'm +1 on this, I suspect there may be others who would strongly disagree with having it as part of the core.

Cal


--
You received this message because you are subscribed to the Google Groups "Django developers" group.
To post to this group, send email to django-d...@googlegroups.com.
To unsubscribe from this group, send email to django-develop...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-developers?hl=en.


Reply all
Reply to author
Forward
0 new messages