Dakkar
Dakkar

Reputation: 5952

Flask: dynamically populated form from databse content

basically I want to do something quite simple: I want to create a form for deleting entries in a database.

the template is creating a html table with all entries without any trouble. My problem now is: how to convert this to a form with a link in every row.

Of course I could do the manual way of writing html code with a link. But is there a more "flaskish" way? I'm already using wtforms and sqlalchemy

My route:

@app.route('/admin', methods=['GET', 'POST'])
@htpasswd.required
def admin(user):
    orders = Order.query.all()

    return render_template(
        'admin.html', title="AdminPanel", orders=orders
    )

The model:

class Order(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(120), index=True, unique=True)

The template:

{% for order in orders %}
            <tr>
                <td>{{order.email}}</td> 
                <td><a href="{{ url_for('admin',order_id=order.id, action='delete') }}"><i class="fa fa-trash" aria-hidden="true"></i></a></td>
            </tr>
 {% endfor %}

Upvotes: 1

Views: 303

Answers (1)

shifloni
shifloni

Reputation: 719

You should use a different route for deletion and not the same one you are using to render the template. Also you do not need a form for the deletion task. You can use get parameters for that and links like you have tried

add this to your routes:

from flask import redirect, url_for
from app import db # you should import your db or db session instance so you can commit the deletion change this line to wherever your db or db session instance is


@app.route('/delete/<order_id>', methods=['GET', 'POST'])
@htpasswd.required
def delete(order_id):
    orders = Order.query.filter(Order.id == order_id).delete()
    db.commit()
    return redirect(url_for('admin'))

Basically you will perform a delete and then redirect back to the admin route with the above code

Your template file should be changed to:

{% for order in orders %}
            <tr>
                <td>{{order.email}}</td> 
                <td><a href="{{ url_for('delete',order_id=order.id) }}"><i class="fa fa-trash" aria-hidden="true"></i></a></td>
            </tr>
 {% endfor %}

Upvotes: 2

Related Questions