Categories
Python Answers

How to iterate over model instance field names and values in template with Python Django?

Spread the love

Sometimes, we want to iterate over model instance field names and values in template with Python Django.

In this article, we’ll look at how to iterate over model instance field names and values in template with Python Django.

How to iterate over model instance field names and values in template with Python Django?

To iterate over model instance field names and values in template with Python Django, we can use a for loop.

For instance, we write

from django.forms.models import model_to_dict


def show(request, object_id):
    object = FooForm(data=model_to_dict(Foo.objects.get(pk=object_id)))
    return render_to_response("foo/foo_detail.html", {"object": object})

in the show view that passes the object object to the foo_detail.html template.

Then in the template, we write

{% for field in object %}
    <li><b>{{ field.label }}:</b> {{ field.data }}</li>
{% endfor %}

to loop through the object attributes and get the attribute name from label and the attribute value from data.

Conclusion

To iterate over model instance field names and values in template with Python Django, we can use a for loop.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *