Reputation: 427
I want to make sure I'm following best practices here. I have a table of data that pulls from the database and in the last column I have links to edit or delete that row. I feel like I've always been told to never modify data on the server with a GET request. How would I handle deleting this data row with anything other than a GET request? Here's the code for the data table:
<table class="table table-hover notifications">
<thead><tr><th>Search Parameter</th><th>Subreddits</th><th>Actions</th></thead>
{% for notification in notifications %}
<tr>
<td>{{ notification.q }}</td>
<td>{% for s in notification.subreddits %} {{ s.r }}<br> {% endfor %}</td>
<td><a href="{{ url_for('main.edit_notification', id=notification.id) }}">Edit</a> | <a href="">Delete</a></td>
</tr>
{% endfor %}
</table>
I guess I'm not sure how to approach building the url for Delete. I can build a delete method and pass the id of the element I want to delete (ex: /delete/1), but is that not modifying data with a GET request then?
Upvotes: 2
Views: 6203
Reputation: 3554
You can create a form that makes a POST request on submit, connected to a view that deletes the object when request.method
is POST (passing the object ID in the URL, as you said).
I am not a Flask expert, but taking this code as example, your view should look something like:
@app.route('/delete/<int:id>', methods=['POST'])
def remove(id):
object = Object.query.get_or_404(id)
delete(object)
return redirect(url_for('index'))
And your form like:
<form method="post" action="{{ url_for('remove', id=object.id) }}">
<button type="submit">Delete</button>
</form>
The form action
attribute forces the form to submit its information to the given URL/view.
Upvotes: 4