This question has an answer here, but it is outdated and incorrect as it does not work in a template.
I am using a standard ListView
to access objects in a template. I want to display my objects in a table with field names in the header and field values in the table body.
To do this, is fairly straightforward, but I am not sure how to access the object field name. You can't use {{ object._meta.get_field[field].verbose_name }}
as _meta
is not available in templates.
For example: First I add a list of the fields I want to render to the context:
def get_context_data(self, **kwargs):
context['fields'] = ['id', 'email', 'name']
Then I loop them in the template:
<table>
<thead>
{% for object in object_list %}
{% if loop.first %}
<tr>
{% for field in fields %}
// MISSING CODE //
{% endfor %}
</tr>
{% endif %}
{% endfor %}
</thead>
<tbody>
{% for object in object_list %}
<tr>
{% for field in fields %}
<td>{{ object[field] }}</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
This works well in that it displays just the fields I want in the body, but somehow I need to access the field verbose name on the object. I guess I could pass a dict
in my context instead of a list (with field:verbose_name
key:value pairs) , but this doesn't feel very DRY.
Any ideas?