Problem to show single row table in python flask

0

Issue

I want to show a table in the html using python flask framework. I have two array. One for column heading and another for data record. I am able to show the table perfectly when I have two or more records. However, if I have only one row then table formation is not right. How to fix this problem? Could help me to solve this?
enter image description here
enter image description here

table.py

from flask import Flask, request, render_template

app = Flask(__name__)

@app.route('/')
def my_form():

    headings = ("name", "role", "salary")
    data = (("rolf", "software engineer", "4500"), ("neu", "civil engineer", "1500"), ("neu", "civil engineer", "1500"))

    return render_template('table2.html', data=data, headings=headings)

table2.html

<table>
<tr>
{% for header in headings %}
       <th>{{ header }}</th>
        {% endfor %}
    </tr>
    {% for row in data %}
    <tr>
    {% for cell in row %}
    <td>{{ cell }}</td>
    {% endfor %}
    </tr>
    {% endfor %}
</table>

Solution

This code seems to fail with a single record defined incorrectly as:

data = (("rolf", "software engineer", "4500")) # incorrect

The fix is to include the trailing comma for the outer tuple, which must be done when a tuple contains only one item:

data = (("rolf", "software engineer", "4500"),)

‘Why’ can be demonstrated in the python shell:

>>> data = (("rolf", "software engineer", "4500"))
>>> data
('rolf', 'software engineer', '4500')
>>> data[0]
'rolf'
>>> # etc ...
... 
>>> data = (("rolf", "software engineer", "4500"),)
>>> data
(('rolf', 'software engineer', '4500'),)
>>> data[0]
('rolf', 'software engineer', '4500')
>>> 

In the template, a string is reaching the loop: {% for cell in row %} where cell is each character in that string, instead of an individual item from the inner tuple.

Answered By – v25

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More