Loop through the field names and values of a model instance in a template

Posted by

In this tutorial, we will learn how to iterate over model instance field names and values in a Django template using HTML tags. This can be useful when you want to display all the fields and corresponding values of a model instance in your template.

First, let’s start by creating a simple Django model to work with. Suppose we have a model named Book with fields such as title, author, and published_date. Here’s how the model might look like:

from django.db import models

class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.CharField(max_length=50)
    published_date = models.DateField()

Next, let’s create a view function that retrieves a specific Book instance from the database and passes it to a template for rendering. Here’s how the view might look like:

from django.shortcuts import render
from .models import Book

def book_detail(request, book_id):
    book = Book.objects.get(pk=book_id)
    return render(request, 'book_detail.html', {'book': book})

Now, let’s create the HTML template book_detail.html where we want to display all the fields and values of the Book instance. We will use HTML tags and Django template tags to iterate over the model instance fields. Here’s the template code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Book Detail</title>
</head>
<body>
    <h1>{{ book.title }}</h1>
    <ul>
        {% for field, value in book.__dict__.items %}
            {% if not field.startswith('_') %}
                <li><strong>{{ field|title }}</strong>: {{ value }}</li>
            {% endif %}
        {% endfor %}
    </ul>
</body>
</html>

In the template, we first display the book’s title using {{ book.title }}. Then, we use the {% for %} loop to iterate over all the fields and values of the Book instance. We access the fields and values using book.__dict__.items which returns a dictionary containing all the field names and their corresponding values.

Inside the loop, we check if the field name does not start with an underscore (which are internal attributes) using {% if not field.startswith('_') %}. We then display the field name in uppercase format using the {{ field|title }} filter and the value of the field using {{ value }}.

Finally, when you navigate to the book_detail view in your Django application, you will see the HTML template displaying all the fields and corresponding values of the selected Book instance.

This is how you can iterate over model instance field names and values in a Django template using HTML tags. I hope you found this tutorial helpful! Let me know if you have any questions.