user122434 user122434 - 1 year ago 74
HTML Question

Loop in django with 2 parameter

I am new to

, I have passed two list(
) to my template, and then I want to have a loop like this :(it is the logic of my aim, the syntax is not correct)

<div ,id="menuFood>

but when i searched, i can find only loop like this:

{% for o in some_list %}
{% endfor %}

so with this syntax , I can't understand how to create that loop. I think only nested loop can make by this syntax..

here is my view code :

def foods(request):
food = Food.objects.all()
raw = [];
return render(request, 'polls/foods.html', {'food': food,'rawmaterial': raw})

Answer Source

You can't do index on django template, but you could just put 2 lists together in your using zip function:

food = Food.objects.all()
raw = []
# ...

result = zip(food, raw)
return render(request, 'polls/foods.html', {'result': result})

Then in your template:

{% for food, raw in result %}
<h4>{{ food }}</h4>
<h4>{{ raw }}</h4>
{% endfor %}

By the way, you seems to come from java/c++ background because in python people never do:

for(i=0; i<food.length; i++)
    print food[i]

instead, we do:

for i in food:
    print i

Django template is adopting the similar syntax, it makes writing a loop a lot easier.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download