'Slice a list with for loop range function in Django templates
I am developing a Django application about statistics calculations. But now I have faced a problem that I can't solve. I have two lists in my views.py list1 = [5, 6, 7, 8] list2 = [5, 6, 7, 8]. I sent this to Django templates and I also sent 'n' : range(7) as context.
In my html code, there have a code
<table>
<thead>
<tr>
<th>list1</th>
<th>list2</th>
</tr>
<tr>
<td></td>
<td></td>
</tr>
</thead>
</table>
Now I want to print first value of each list in first row, then second value of each list in second row and so on.
So I have made a code something like this
<table>
<thead>
<tr>
<th>list1</th>
<th>list2</th>
</tr>
{% for i in n %}
<tr>
<td> {{ list1.i }} </td>
<td>{{ list2.i }}</td>
</tr>
{% endfor %}
</thead>
</table>
After writting this code, I am not getting any error but the values are not showing. Instead a blank row and columns are being made.
Please help me to print the values that I want to print.
Solution 1:[1]
As a general rule, you should keep all the logic on views. What I'd do is zip the lists and use tuples instead.
views.py:
new_list = zip(list1, list2)
context = {
'new_list': mylist,
}
and on templates:
{% for list1_item, list2_item in new_list %}
<tr>
<td> {{ list1_item }} </td>
<td> {{ list2_item }}</td>
</tr>
{% endfor %}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | almanegra |
