mycognosist
mycognosist

Reputation: 143

Creating an HTML table with database values in Flask

I want to display a table showing the values of three fields for each of the units in a table. Some assistance with creating the dictionary from the database and passing objects to the template would be greatly appreciated.

@app.route('/')
def index(row):
    unit_count = Units.query.count()
    unit = Units.query.filter_by(id=row).first()
    rows = [] # Unsure how to define rows from Units db table
    return render_template('table_overview.html', title='Overview', rows=rows, unit=unit)
{% for row in rows %}
<tr>
    <td>{{ row.unit.idnum }}</a></td>
    <td>{{ row.unit.product_code }}</td>
    <td bgcolor="{{ row.unit.stat_colour }}">{{ row.unit.unit_status }}</td>
</tr>
{% endfor %}

Upvotes: 5

Views: 13456

Answers (1)

abigperson
abigperson

Reputation: 5362

First off your view function can't receive the row input you specify. If you're trying to show all rows in the table you can do it like this:

views.py:

@app.route('/')
def index():
    rows = Units.query.all()
    return render_template('table_overview.html',
                            title='Overview',
                            rows=rows)

table_overview.html (template)

    {% for row in rows %}
    <tr>
        <td>{{ row.idnum }}</a></td>
        <td>{{ row.product_code }}</td>
        <td bgcolor="{{ row.stat_colour }}">{{ row.unit_status }}</td>
    </tr>
    {% endfor %}

Upvotes: 7

Related Questions