1

In my Django/Python application I am passing multiple iterable objects from views.py to index.html. I am essentially trying to make a standard for loop in which you can get an item by its index. Once I am iterating through the first object, how can I get the respective index of another iterable in that same loop?

Conditions: All of the arrays will always be equal in length, but their length will change on a daily basis.


views.py

name = ['John', 'Kim', 'Tim', 'Jill']
age = ['20', '30', '52', '27']
state = ['IN', 'IL', 'CA', 'TX']
city = ['Muncie', 'Champaign', 'Fresno', 'Dallas']

def index(request):
    args = {'names': name, 'ages': age, 'states': state, 'cities': city}
    return render(request, 'index.html', args)

index.html

{% extends 'base.html' %}
{% load staticfiles %}

{% block Data %}
    {% for name in names %}
        <p>{{ name }}</p>
        <p>{{ age.forloop.counter0 }}</p>
        <p>{{ state.forloop.counter0 }}</p>
        <p>{{ city.forloop.counter0 }}</p>
    {% endfor %}
{% endblock %}

As you can see, I thought I would use 'forloop.counter0' as my index. But it doesn't work that way apparently. Any suggestions on how to achieve this goal? Thanks in advance!

2 Answers 2

1

You can zip the lists in the view and unpack them in the template:

def index(request):
    data = zip(name, age, state, city)
    args = {'data': data}
    return render(request, 'index.html', args)

And then in the template:

{% for name, age, state, city in data %}
    {{ name }}
    {{ age }}
    {{ state }}
    {{ city }}
{% endfor %}

You could also use objects, or named tuples, with the appropriate attributes.

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

Comments

0

I think what you are looking for is the "for loop counter". You can use {{ forloop.counter }} index start at 1 or {{ forloop.counter0 }} index start at 0.

{% for item in list %}
    {% if forloop.counter == 1 %}
       Do something
    {% endif %}
{% endfor %}

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.