Home > database >  how to render values from multiple methods in table format in template django
how to render values from multiple methods in table format in template django

Time:12-16

I have a django app.

And I have two methods:

def total_cost_fruit(self):
        return [3588.20, 5018.75, 3488.16]
    
    def total_cost_fruit2(self):
        return [3588.20, 5018.75, 3488.99]

And I try to render them as table.

so this is the views.py:

def test(request):
  
    values1 = filter_text.total_cost_fruit()
    values2 = filter_text.total_cost_fruit2()
   
    context = {
     
        "values1": values1,
        "values2": values2,
        "all_values": list(chain(values1, values2)),
    } 

    return render(request, "main/test.html", context)

and template:

<div >
    <table>
    <tr>
    <th>Method 1</th>
    <th>Method 2</th>
                    
    </tr>
    {% for value in all_values %}
   <tr>
  <td>{{value.0}}</td>
  <td>{{value.1}}</td>
                            
  </tr>
 {% endfor %}
  </table>
</div>

But nothing is displayed

CodePudding user response:

It should work this way as long as len(values1) == len(values2):

def test(request):
    values1 = filter_text.total_cost_fruit()
    values2 = filter_text.total_cost_fruit2()
   
    context = {
        "all_values": [[values1[i], values2[i]] for i in range(len(values1))],
    } 

    return render(request, "main/test.html", context)

Otherwise, if len(values1) != len(values2):

def test(request):
    values1 = filter_text.total_cost_fruit()
    values2 = filter_text.total_cost_fruit2()

    context = {
        "all_values": [
        [
            values1[i] if i < len(values1) else "",
            values2[i] if i < len(values2) else "",
        ]
        for i in range(max(len(values1), len(values2)))
    ],
    }

    return render(request, "main/test.html", context)
  • Related