ng150716
ng150716

Reputation: 2244

Using multiple for tags in tables with django

I'm fairly new to Django, and am working on a project where I have items appended to multiple lists and would like to display them in a table. I am using the for tag as there is quite a few items in each list. However, when i run my code, the first item on the list repeats over and over, then the second item repeats over and over, and so on. I have a feeling its because i used multiple for tags. Heres my code:

<table>
{% for x in result.netIncomeAr %}
{% for y in result.d2 %}    
<tr>    
    <td>{{ x }}</td>
    <td>{{ y }}</td>
</tr>
{% endfor %}
{% endfor %}
</table>

Any ideas where I went wrong? Thanks.

Upvotes: 1

Views: 50

Answers (1)

alecxe
alecxe

Reputation: 473863

The inner loop should use the outer loop variable:

{% for x in result.netIncomeAr %}
    {% for y in x.d2 %} 

UPD (after looking at the result variable):

You need to change the result variable passed into the template, use zip() to join two lists:

result = zip(df['Date'], df['Net Income'])
return render_to_response('ui/search.html', {"result": result},  context)

Then, in the template iterate over the result this way:

<table>
    {% for x in result %}
    <tr>    
        <td>{{ x.0 }}</td>
        <td>{{ x.1 }}</td>
    </tr>
    {% endfor %}
</table>

Upvotes: 2

Related Questions