Reputation: 71
I am populating a table and want to allow users to be able to delete data as they see fit. How can I retrieve the row values they want to delete server side? I am populating the table through a list as such:
<tr>
<td> {{ key }} </td>
<td> {{ value[1] }}</td>
<td> {{ value[0] }}</td>
<td> {{ value[2] }}</td>
<td> {{ value[3] }}</td>
<td> {{ value[4] }}</td>
<td> <button id="remove" value="Delete" name="btn2">Delete</button><td>
</tr>
Upvotes: 0
Views: 127
Reputation: 5442
You can create a view that will take an id
as an argument and then create a link in a template that will point to that view; or, even better, since you added a jquery
tag to your question, create an AJAX request. I'd use a DELETE
HTTP request for that since RESTful way is pretty much better, but you can get away with either GET or POST.
@app.route('/delete/<int:id>', methods=['GET', 'POST', 'DELETE'])
def delete_data(id=None):
if id is None:
return 'Please provide an object ID to delete!'
object_to_delete = db.session.query(Data).filter_by(id=id)
db.session.delete(object_to_delete)
db.session.commit()
And then, in the template,
<a href="{{ url_for('delete', id=key) }}">Delete!</a>
Please note that I provided the easiest (but not really secure and/or proper) way. An AJAX request, while having a lot more code on the client-side :), would be really much better. There's a Flask Mega-Tutorial article that covers AJAX.
Upvotes: 2