3

I was trying to iterate a list_length in a for loop. The list_length is an int object which is passed as a context variable to the template. But when I try to do that it gives this typeError. Can someone help?

{% for i in list_length %}
    <tr>
        <td>{{ i }}</td>
    </tr>
{% endfor %}
creyD
  • 1,972
  • 3
  • 26
  • 55
Aamy
  • 123
  • 1
  • 3
  • 9

2 Answers2

5

I think you are trying to print index of every row in the table. For that you have to iterate over a list of indices. Create this list in your django view

list = []
for i in range(0,list_length):
    list.append(i)

Then pass this list in your django template and iterate over it

{% for i in list %}
    <tr>
        <td>{{ i }}</td>
    </tr>
{% endfor %}

This should work for you.

Naman Sogani
  • 943
  • 1
  • 8
  • 28
0

A list itself may be iterable, but a single integer on its own is not a list.

If you want to iterate from zero up to an integer, you can use something like Python's range(n) to create an iterator for those values. That's for naked Python, Django appears to require a slightly more complex method, as per Numeric for loop in Django templates.

Otherwise, you possibly need to iterate over the list itself rather than its length (depending on what you're trying to do and whether you need a list 'index' within the loop).

Community
  • 1
  • 1
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • when i try `{% for i in range(list_length) %}` it gives `TemplateSyntaxError :Could not parse the remainder: '(list_length)' from 'range(list_length)'` – Aamy Jun 24 '15 at 05:34
  • @user3496949, the key phrase there was 'like Python's range ...' :-) Have updated with a link to another SO question showing how to do same in Django, no use repeating that info here. – paxdiablo Jun 24 '15 at 05:42