Home > front end >  Django how do you loop using range through two lists simultaneiously
Django how do you loop using range through two lists simultaneiously

Time:11-11

I'm working with Django and would like to iterate through two lists so that the're side by side: my views file:

def displayDict(request):
     data = ["a", "b", "c"]
     data2 = ["x", "y", "z"]
     return render(request, 'chattr.html',
     {'range': range(0,len(data)-1),'dictItems': data, "otherDict" : "other_bot", "dictItems_bot": data2, "otherDict2": "bot" , "duo" : (data, data2)})

my template:

{% for i in range %}
    <p>
        {{i}} <br>
        <b>{{otherDict}}:</b> {{dictItems.i}} <br>
        <b>{{otherDict2}}:</b> {{dictItems_bot.i}} <br>
        {% comment %} {{a|add:1}} {% endcomment %}
    </p>
{% endfor %} 

I'd like a webpage that looks like:
other_bot: 'a'
dictItems_bot: 'x'
other_bot: 'b'
dictItems_bot: 'y'
other_bot: 'c'
dictItems_bot: 'z'

Currently nothing renders except the bot names:
other_bot:
dictItems_bot:
other_bot:
dictItems_bot:

I may also be able to do this inner loop using tuples, Django Template: looping through two lists. But this would be a lot more complex,...

CodePudding user response:

try this...

view.py

def display_dict(request):
    data = ["a", "b", "c"]
    data2 = ["x", "y", "z"]
    context = {"data": zip(data, data2), "otherDict": "other_bot","otherDict2": "dictItems_bot"}
    return render(request, 'home.html', context)

HTML

{% for element in data %}
    <p><b>{{ otherDict }}:</b>{{ element.0 }}</p>
    <p><b>{{ otherDict2 }}:</b>{{ element.1 }}</p>
{% endfor %}

CodePudding user response:

For these sorts of issues I have Django Debug Toolbar installed, which lets me see the context. I suspect your 'range' has an issue because {{i}} is not being rendered (or is it?), so you are just looping once instead of thrice, i.e. not looping at all.

  • Related