Reputation: 15
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 !!
Upvotes: 0
Views: 388
Reputation: 2002
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.
Upvotes: 2
Reputation: 313
You change your view to this:
def fadakpage(request):
j = 0
tours = []
for i in tour.objects.order_by('tourleader'):
tours.append((i, j))
j += 1
args = {'tours': tours, 'range': range(j)}
return render(request, 'zudipay/fadakpage.html', args)
And use list of tuples in your template:
{% for tour in tours %}
{{ tour.0.tourleader }}
{% endfor %}
In this code in your template {{ tour.0 }}
is tour
object and {{ tour.1 }}
is count.
Upvotes: 0
Reputation: 599600
No, indeed, that does not work in a Django template. But there is no reason to do it: just loop through tours
.
{% for tour in tours %}
{{tour.tourleader}}
{% endfor %}
Upvotes: 1