Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting rows from database with python flask?

I am using a flask framework, and can't seem to delete rows from the database. The code below gives a 405 error: "The method is not allowed for the requested URL." Any ideas?

In the py:

@app.route('/delete/<postID>', methods=['POST'])
def delete_entry():
    if not session.get('logged_in'):
        abort(401)
    g.db.execute('delete from entries WHERE id = ?', [postID])
    flash('Entry was deleted')
    return redirect(url_for('show_entries', post=post))

In the html:

<a href="/delete/{{ entry.id }}"><h3>delete</h3></a>
like image 612
Hayley van Waas Avatar asked Mar 19 '23 10:03

Hayley van Waas


2 Answers

Clicking <a href...>delete</a> will issue a GET request, and your delete_entry method only responds to POST.

You need to either 1. replace the link with a form & submit button or 2. have the link submit a hidden form with JavaScript.

Here's how to do 1:

<form action="/delete/{{ entry.id }}" method="post">
    <input type="submit" value="Delete />
</form>

Here's how to do 2 (with jQuery):

$(document).ready(function() {
    $("a.delete").click(function() {
        var form = $('<form action="/delete/' + this.dataset.id + '" method="post"></form>');
        form.submit();
    });
});

...

<a href="#delete" class="delete" data-id="{{ entry.id }}">Delete</a>

One thing you should not do is make your delete_entry method respond to GET. GETs are meant to be idempotent (are safe to run repeatedly and don't perform destructive actions). Here's a question with some more details.

like image 108
Steven Kryskalla Avatar answered Apr 02 '23 13:04

Steven Kryskalla


Alternatively, change POST to DELETE to get you going.

@app.route('/delete/<postID>', methods=['DELETE'])

Ideally, you should use HTTP DELETE method.

like image 25
chfw Avatar answered Apr 02 '23 13:04

chfw