0

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 !!

2
  • Do you require the index in your loop? If not, then Daniel Roseman's answer is all you need Commented Jul 30, 2019 at 8:06
  • yes i saw his answer but yes i need the index . Commented Jul 30, 2019 at 8:09

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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 %}

1 Comment

i know that but I have summarized my code. in continue i need the index of a tour in tours!
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.