TYL TYL - 3 years ago 192
Python Question

Python Django Jinja2: How to use the range value within the for-loop statement as the index of a list?

I trying to display the items within a list. This is my code:

#Django view.py file
def display(request):
listone = ['duck', 'chicken', 'cat', 'dog']
lents = len(list_one)
listtwo = ['4 dollars', '3 dollars', '2 dollars', '1 dollars']
return render(request, 'display.html', {'itemone' : listone, 'itemtwo' : listtwo, 'lents' : lents})


This is the display.html file that display the list:

<table>
<tr>
<th>Pet</th>
<th>Price</th>
</tr>
{% for numbers in lents %}
<tr>
<td>{{ itemone.numbers }}</td>
<td>{{ itemtwo.numbers }}</td>
</tr>
{% endfor %}
</table>


but with no luck it won't show the result according to the index 'numbers' which suppose to be from '0' to '3' the 'td' tags remaining empty.

Answer Source

A better option is to create a zip object in your view, to match the pet to a price, and pass only this to the template :

def display(request):
   listone = ['duck', 'chicken', 'cat', 'dog']
   listtwo = ['4 dollars', '3 dollars', '2 dollars', '1 dollars']
   fusion = zip(listone, listtwo)
   return render(request, 'display.html', {'fusion' : fusion})

Then you can unpack it in your template, zip() will produce a list of tuples (name, price) and you can easily loop on this :

<table>
   <tr>
     <th>Pet</th>
     <th>Price</th>
   </tr>
   {% for name, price in fusion %}
      <tr>
        <td>{{ name }}</td>
        <td>{{ price }}</td>
      </tr>
   {% endfor %}
</table>

Another solution is to create a new custom template filter, there are already some posts explaining the process : https://stackoverflow.com/a/29664945/6655211

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download