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