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


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 %}
                <td>{{ book.0 }}</td>
                <td>{{ book.1 }}</td>
                <td>{{ book.2 }} </td>
                <td>{{ book.3 }}</td>
        {% 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 %}
                <td>{{ book.id }}</td>
                <td>{{ book.name }}</td>
                <td>{{ book.author }} </td>
                <td>{{ book.copies }}</td>
        {% endfor %}

Leave a comment