0

I have a form, that accepts a number. On submission of the form, this number is redirected to another html page from the django views.py. Here, how do I iterate over the number that I have received? When I try with the below, it says 'int' object is not iterable

{% for i in N %}
 <p>{{i}}</p>
{% endfor %}

Note: N here is the number received from the form.

Arun George
  • 1,167
  • 3
  • 15
  • 29

1 Answers1

0

The reason why you get this error is because a number can not be iterated over. In python you would have to use range(N) like this:

for i in range(N):
    print(i)   

The template language from django does not have a for .. in range .. functionality. What you are looking for is a custom filter that you would have to load.

You would have to create a new file called my_filters.py and register all the filters you need.

from django import template

register = template.Library()

@register.filter(name='times')
def times(number):
    return range(number)

In the templates use this:

{% load my_filters %}
{% for i in N|times %}
    <p>{{i}}</p>
{% endfor %}

Find more information here

Arun George
  • 1,167
  • 3
  • 15
  • 29
Anna M.
  • 400
  • 2
  • 9