Ad

Django Templates Index Of Array Does Not Work

- 1 answer

Index in templates of django is like this: {{somearray.i}} for my code this is not working!!

this is views.py

def fadakpage(request):
    tours = tour.objects.order_by('tourleader')
    travelers = traveler.objects.order_by('touri')
    j=0
    for i in tours:
        j+=1
    args={'tours':tours,'travelers':travelers,'range':range(j)}
    return render(request,'zudipay/fadakpage.html',args)

this is fadakpage.html / template (it shows empty):

{% for i in range %}
      {{tours.i.tourleader}}
{% endfor %}

but if i change {{tours.i.tourleader}} to {{tours.0.tourleader}} it works!! I also checked I values and it was true !!

Ad

Answer

Not sure if this is exactly what you need. You can get the loop counter by using {{ forloop.counter }} to get the loop index starting at 1, or {{ forloop.counter0 }} to get the index starting at 0.

{% for tour in tours %}
      {{ tour.tourleader }} {{ forloop.counter }}
{% endfor %}

See the docs for more info.

Ad
source: stackoverflow.com
Ad