1

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
    }
Amit Pal
  • 10,604
  • 26
  • 80
  • 160

3 Answers3

1

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)]

Goin
  • 3,856
  • 26
  • 44
  • I have some like this: ***{% for x, value in obj1_and_obj.iteritems %}*** Actual in one loop i am loading values of a dictionary and from one loop i am loading form the list. Is there any error with the code? – Amit Pal Jun 26 '12 at 12:05
0

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 %}
Ahsan
  • 11,516
  • 12
  • 52
  • 79
  • Hey, have you checked the ***share_user.id*** in reverse of that url. That is the reason i want to do that because i also want to get the value of share_user.id , which comes from this loop ***{% for share_user in objects %}***. That's is the only reason i want to do that. – Amit Pal Jun 26 '12 at 13:53
  • @AmitPal Sorry i forgot to change it, check it now – Ahsan Jun 26 '12 at 13:56
0

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

theshubhagrwl
  • 743
  • 9
  • 17