How to show content with zip in view with django?

Question:

I hava a django applicaiton. And I try to show the content values from the backend in the template. There is a method: show_extracted_data_from_file where I combine three methods:


class FilterText:

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


    def show_extracted_data_from_file(self):

   regexes = [
            self.total_cost_fruit(),
            self.total_cost_fruit2(),
            self.total_cost_fruit3,
        ]
        matches = [(regex) for regex in regexes]

        return zip(matches)

and I have the view:


def test(request):


    content_pdf = ""   
    filter_text = FilterText()     
    content_pdf = filter_text.show_extracted_data_from_file()   
    context = {"content_pdf": content_pdf}
    return render(request, "main/test.html", context)

and html:

<div class="wishlist">
   <table>
      <tr>
         <th>Method 1</th>
         <th>Method 2</th>
         <th>Method 3</th>
      </tr>
      {% for value in content_pdf %}
      <tr>
         <td>{{value.0}}</td>
         <td>{{value.1}}</td>
         <td>{{value.2}}</td>
      </tr>
      {% endfor %}
   </table>
</div>

But it looks now:

Method 1    Method 2    Method 3
[3588.2, 5018.75, 3488.16, 444]         
[3588.2, 5018.75, 3488.99]      
[3588.2, 5018.75, 44.99]

But I want it of course under each other:

Method 1    Method 2    Method 3
3588.2           3588.2            3588.2
5018.75,         44.99              3488.99 
5018.75,       
5018.75 
3488.16
444
Asked By: mightycode Newton

||

Answers:

You can work with itertools.zip_longest(…) [Python-doc] to put None values when one of the methods end, so:

from itertools import zip_longest


class FilterText:
    def total_cost_fruit(self):
        return [3588.20, 5018.75, 3488.16, 444]

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

    def total_cost_fruit3(self):
        return [3588.20, 5018.75, 44.99]

    def show_extracted_data_from_file(self):
        regexes = [
            self.total_cost_fruit(),
            self.total_cost_fruit2(),
            self.total_cost_fruit3(),
        ]
        return zip_longest(*regexes)

You can also render this more conveniently with:

<div class="wishlist">
   <table>
      <tr>
         <th>Method 1</th>
         <th>Method 2</th>
         <th>Method 3</th>
      </tr>
      {% for value0, value1, value2 in content_pdf %}
      <tr>
         <td>{{ value0 }}</td>
         <td>{{ value1 }}</td>
         <td>{{ value2 }}</td>
      </tr>
      {% endfor %}
   </table>
</div>
Answered By: Willem Van Onsem
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.