[Solved]-How to iterate over a list in django templates?

22👍

Zip all your lists to one list of tuples:

 books= zip(ID, bookName, author, copies)
 return render(request, 'allbooks.html',{ "books": books} )

Than loop over it in templates like:

             {% for book in books %}
            <tr>
                <td>{{ book.0 }}</td>
                <td>{{ book.1 }}</td>
                <td>{{ book.2 }} </td>
                <td>{{ book.3 }}</td>
            </tr>
        {% endfor %}

I suggest a better structure for your book info:

books = [

{ "id":1, "name": "Python", "author":"idk", "copies": 1},
{ "id":2, "name": "Java", "author":"idk2", "copies": 3}

]

than iterate through it:

       {% for book in books %}
            <tr>
                <td>{{ book.id }}</td>
                <td>{{ book.name }}</td>
                <td>{{ book.author }} </td>
                <td>{{ book.copies }}</td>
            </tr>
        {% endfor %}
👤Assem

Leave a comment