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

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:

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

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.

10/2/2014 11:54:19 AM

Accepted Answer

model._meta.get_all_field_names() will give you all the model's field names, then you can use model._meta.get_field() to work your way to the verbose name, and getattr(model_instance, 'field_name') to get the value from the model.

NOTE: model._meta.get_all_field_names() is deprecated in django 1.9. Instead use model._meta.get_fields() to get the model's fields and to get each field name.

7/31/2015 10:36:13 PM

You can use Django's to-python queryset serializer.

Just put the following code in your view:

from django.core import serializers
data = serializers.serialize( "python", SomeModel.objects.all() )

And then in the template:

{% for instance in data %}
    {% for field, value in instance.fields.items %}
        {{ field }}: {{ value }}
    {% endfor %}
{% endfor %}

Its great advantage is the fact that it handles relation fields.

For the subset of fields try:

data = serializers.serialize('python', SomeModel.objects.all(), fields=('name','size'))

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow