How to retrieve index number from a 'for' loop of a dict in Django Views

I am trying to get the index number of {% for p in mydict_1 %} so that I can use that index on another dict to get the value. I want to use p as an index number. How to do this within Django Views? Data from both lists corresponds to the index in a series.

mylist_1 = [{'itemCode': 'AZ001', 'price': 15.52}, {'itemCode': 'AB01', 'price': 31.2}, {'itemCode': 'AP01', 'price': 1.2}] #list of dict
mylist_2 = [{'prop': 'val000'}, {'prop': 'val008'}, {'prop': 'val009'}] #list of dict

{% for p in mylist_1 %}
       #Want to use p's index number to get value of that index from mylist_2
       <td><a>{{mylist_2.[p].prop}}</a></td> #How to do this correctly? Expecting val000 for index 0
{% endfor %}

Submitted January 01st 2021 by Admin


You don't. Django's template language deliberately restricts that to prevent people writing business logic in the template. You can pass the dictionaries with zip(…) [python-doc] to the template:

def my_view(request): # … context = { # …, 'mydicts': zip(mydict_1, mydict_2) } return render(request, 'some-template.html', context)

in the template you then iterate with:

{% for p, q in mydicts %} {{ p.itemCode }} {{ p.price }} {{ q.prop }}
{% endfor %}

Admin | 9 months ago

Relevant Questions