7

I'm working with a Flask framework, and am trying to delete an entry from the database. The code below gives this error: "The method is not allowed for the requested URL."

In the html:

<form action="{{ url_for('delete_entry', id=entry.id) }}" method="POST">
     <input type="hidden" name="_method" value="DELETE" />
     <input type="submit" value="Delete entry" />
</form>

In the py:

@app.route('/delete', methods=['DELETE'])
def delete_entry(postID):
    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'))

How do I then get the correct postID from the html to the py?

Hayley van Waas
  • 429
  • 3
  • 12
  • 21
  • 1
    The method referenced in your route decorator should be POST and not DELETE. – b10n Sep 19 '14 at 01:40
  • @b10n thanks, and what about getting the postID to the function? How do I do that? – Hayley van Waas Sep 19 '14 at 01:58
  • Several good responses here: [http://stackoverflow.com/questions/25947251/deleting-rows-from-database-with-python-flask/](http://stackoverflow.com/questions/25947251/deleting-rows-from-database-with-python-flask/) – fundatillus May 15 '16 at 18:52

2 Answers2

4

If you are going to use a POST request the variable will be available under flask's request.form. If you stay with DELETE I think you need to change your uri. For example:

@app.route('/delete/<int:postID>', methods=['DELETE'])
Wilberto
  • 520
  • 1
  • 4
  • 10
1

To get the postID use this {{ loop.revindex }}

This is my code,it works!!

In the .py:

@app.route('/delete', methods=['POST'])
def delete_entry():
    if not session.get('logged_in'):
        abort(401)
    db = get_db()
    db.execute('delete from entries where id = ?'[request.form['entry_id']])
    db.commit()
    flash('Entry deleted')
    return redirect(url_for('show_entries'))

In the HTML:

<form action="{{ url_for('delete_entry') }}" method=post class=delete-entry>
          <input type="hidden" name="entry_id" value="{{ loop.revindex }}">
          <input type="submit" value="Delete" />
</form>
Kane Lin
  • 31
  • 1
  • 5