Home > Net >  How to use multiple for in template to get elements from object in django
How to use multiple for in template to get elements from object in django

Time:08-27

I am passing below variables from backend. I want to get values dynamically.

num_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] 
answers = [
{'date': datetime.date(2022, 8, 26), 1: 100.0, 2: 50.0, 3: None, 4: None, 5: None, 6: None, 7: None, 8: None, 9: None},
 {'date': datetime.date(2022, 8, 27), 1: 100.0, 2: None, 3: None, 4: None, 5: None, 6: None, 7: None, 8: None, 9: None}
]

In my template I used:

{% for i in answers %}
  <tr>
     <td>{{i.date}}</td>
     {% for j in num_list %}
        <td>{{i.j}}</td>
     {% endfor %}
  </tr>
{% endfor %}

Using the above code in templates is not giving me the output, it just displays empty. but if type manually it works.

<td>{{i.1}}</td>
<td>{{i.2}}</td>
.
.
<td>{{i.9}}</td>

Any Solution to solve this?

CodePudding user response:

You could pack the answers into a separate list, like so:

{'date': datetime.date(2022, 8, 26), "num_list":[100.0, 50.0, None, None, None, None, None, None, None],}

Then in the template, you can easily access the list with:

{% for i in answers %}
...
    {% for j in i.num_list %}
    ....

The above doesn't work, because {{j}} is not an attribute of {{i}}, so you cannot do {{i.j}}

  • Related