Question

I'm trying to get the amount of times these loops have gone into a variable. (I know they're static right now, but eventually they'll be based of data coming from other places).

I know how to do it in other languages, but can't for the life of me figure out how to do it in Python / Django.

In PHP I'd use a i++ in the loop and just display the final value of i

Django 1.5.4 Python 2.7

View

def channel(request):
    values = []
    values2 = []
    for i in range(1,11):
    values.append(i)
    for i2 in range(1,6):
    values2.append(i2)

Template

{% for value in values %}
<insert random html here>
    {{ count_of_loop }}
    {% for value2 in values2  %}
    {{ count_of_loop2 }}
    <insert random html here>
    {% endfor %}
{% endfor %}
Was it helpful?

Solution

If you want to use Counter in template.

{{ forloop.counter }}

A example:

{% for value in values %}
{% if forloop.counter == 1 %}
   Do something.
{% endif %}
{% endfor %}

OTHER TIPS

You can use in the template
{{forloop.counter}} The current iteration of the loop (1-indexed)

{{forloop.counter0}} The current iteration of the loop (0-indexed)

Or if you want to set range within template use | for example:

def channel(request):
    range1 = 11
    range2 = 6


{% for i in 0|range1 %}  
   {{ forloop.counter }}
      {% for y in 0|range2 %}  
         {{ forloop.counter }}
      {% endfor %}  
{% endfor %}  
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top