Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 %}
like image 671
mycognosist Avatar asked Feb 04 '17 12:02

mycognosist


People also ask

How do I create a database table in Flask?

To do this, you can create a function and hook it into a flask command that initializes the database. For now just take a look at the code segment below. A good place to add this function, and command, is just below the connect_db function in flaskr.py : def init_db(): db = get_db() with app.

How fetch data from database in Python and display HTML table?

connector import webbrowser conn = mysql. connector. connect(user='root', password='', host='localhost',database='company') if conn: print ("Connected Successfully") else: print ("Connection Not Established") select_employee = """SELECT * FROM employee""" cursor = conn. cursor() cursor.


1 Answers

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 %}
like image 173
abigperson Avatar answered Sep 29 '22 08:09

abigperson