Dos7
Dos7

Reputation: 3

Flask: How to update HTML table with data from SQLite on homepage after data are saved into db from subpage?

I've got problem with updating data in html table in index.html after I enter them in add.thml

I have homepage where is only table

{% block body %}
    <h1>Project</h1>
    {{ table }}        
{% endblock %}

which is made with flask_table library - it just puts data from SQLite database into html table.

items = Package.select(Package)
table = ItemTable(items)

def populate_table(table):
    items = Package.select(Package)
    table = ItemTable(items)
    return table

I get data from this html form from subpage named add

 <form action=" {{ url_for('save') }}" method="POST">
    Name: <input type="text" name="name">
    <br>
    Dimensions: <input type="text" name="dimensions">
    <br>
    Weight: <input type="text" name="weight">
    <br>
    Status: <input type="text" name="status">
    <input type="submit" name="my-form" value="Submit">
</form>

Then after clicking on submit I run save

@fproject.route('/save', methods=['POST'])
def save():
    text.append(request.form['name'])
    text.append(request.form['dimensions'])
    text.append(request.form['weight'])
    text.append(request.form['status'])
    add_package.add_package_values(text)
    add_package.add_package_to_db(new_package)
    populate_table(table)

    del text[3]
    del text[2]
    del text[1]
    del text[0]

    return redirect(url_for('index'))

it saves values entered by user to database. Then it redirects to homepage (index.html):

@fproject.route('/')
def index():
    context={'table': table}
    return render_template("index.html", **context)

The problem is, that when I come back to index.html I can't see data I enetered in add.html They are in database, but they don't appear in the table. When I restart the app, they are there. But I need them to be there immediately. I tried to put render_template("index.html") into save function, but it still doesn't work. I somehow need html table to be updated or index.html to be rendered again (it will get data from db again - as well the new record I entered at add.html)

How to do that guys ? Thanks

Upvotes: 0

Views: 2696

Answers (1)

Dauros
Dauros

Reputation: 10527

In your save function you are not storing any data in the global table variable. Modify this function like this:

@fproject.route('/save', methods=['POST'])
def save():
    global table

    text.append(request.form['name'])
    text.append(request.form['dimensions'])
    text.append(request.form['weight'])
    text.append(request.form['status'])
    add_package.add_package_values(text)
    add_package.add_package_to_db(new_package)
    table = populate_table(table)

    return redirect(url_for('index'))

I added global table and your populate_table function has a return value, so use it.

Upvotes: 1

Related Questions