Iterate over model instance field names and values in template

I’m trying to create a basic template to display the selected instance’s field values, along with their names. Think of it as just a standard output of the values of that instance in table format, with the field name (verbose_name specifically if specified on the field) in the first column and the value of that field in the second column.

For example, let’s say we have the following model definition:

class Client(Model):
    name = CharField(max_length=150)
    email = EmailField(max_length=100, verbose_name="E-mail")

I would want it to be output in the template like so (assume an instance with the given values):

Field Name      Field Value
----------      -----------
Name            Wayne Koorts
E-mail          [email protected]

What I’m trying to achieve is being able to pass an instance of the model to a template and be able to iterate over it dynamically in the template, something like this:

<table>
    {% for field in fields %}
        <tr>
            <td>{{ field.name }}</td>
            <td>{{ field.value }}</td>
        </tr>
    {% endfor %}
</table>

Is there a neat, “Django-approved” way to do this? It seems like a very common task, and I will need to do it often for this particular project.

23 Answers
23

Leave a Comment