-1

I am new to Django, I have passed two list(rawmaterial and food) 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)

for(i=0;i<food.length;i++)
   <div ,id="menuFood>
   <h4> food.name(i)</h4>
   <h4> rawmaterial.name(i)</h4>
   </div>

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 = [];
    .
    .
    .
    raw.append(warehouse)
    return render(request, 'polls/foods.html', {'food': food,'rawmaterial': raw})
Happy Developer
  • 617
  • 1
  • 8
  • 15

1 Answers1

1

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

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

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.

Shang Wang
  • 24,909
  • 20
  • 73
  • 94