Amit Pal
Amit Pal

Reputation: 11042

How to run multi for loop in Django template?

I have a template in which i need to run two for loop simultanously. For example:

#pseudocode
{% for x in one%} and {% for y in two %}
 {{x}}, {{y}}
{% endfor %}

PS: The above code is pseudo. I also found a package to do it i.e. Djnago-multiforloop

Is there any other way to do it ?

Updated!

I have a dictionary with named objects in python like this:

{<User: x>: True, <User: y>: False}

Now i want to use these value in my Django-template code:

 {% for share_user in objects %} and {% for key, value in objects.iteritems %}
    <tr>
        <td>{{ share_user }}</td> 
        <td><a href="{% url share_edit type type.pk share_user.id %}">{{ value}}</a></td>
    </tr>   
{% endfor %}

I want to merge the two for loop so that the below code in template work successfully.

Desired output: For the first iteration:

x
True

For the second iteration:

Y
False

In my views.py:

 permission_obj = somemodels.objects.filter(object_id=object_id)
 for perm in permission_obj:
    s_user.append(perm.user)
    s_edit.append(perm.edit)
 objects = dict(zip(s_user,s_edit))
 extra_context = {
   'objects' : objects
    }

Upvotes: 1

Views: 3848

Answers (3)

theshubhagrwl
theshubhagrwl

Reputation: 1026

If you want to iterate through 2 lists of same size you can use zip() in python
Please check this answer for the details

https://stackoverflow.com/a/14841466/9715289

Upvotes: 0

Ahsan
Ahsan

Reputation: 11832

According to your update in question.

view.py

permission_obj = somemodels.objects.filter(object_id=object_id)
objects = []

for perm in permission_obj:
   objects.append({'user':perm.user,'edit':perm.edit})

 extra_context = {
   'objects' : objects
    }

template.html

{% for obj in objects %}
    <tr>
        <td>{{ obj.user }}</td> 
        <td><a href="{% url share_edit type type.pk obj.user.id %}">{{ obj.edit }}</a></td>
    </tr>   
{% endfor %}

Upvotes: 0

Goin
Goin

Reputation: 3964

2Only you can do something like this:

{% for x, y in one_and_two %}
   {{x}}, {{y}}
{% endfor %}

If one is [1, 2, 3] and two is [4, 5, 6]

one_and_two is [(1, 4), (2, 5), (3, 6)]

Upvotes: 1

Related Questions