I’m learning Python with the tutorial app from Flask and I can’t figure how to reference a certain row in the database. I m trying to delete a record by using the delete link in the template.I spent a whole day trying everything I could find and to really understand this. I know it’s simple but I don’t get it!
Here’s the html template:
<ul class=entries>
{% for entry in entries %}
<li><h2>{{ entry.title }}
<h2>{{ entry.text|safe }}</h2>
{% if session.logged_in %}
<a href="{{ url_for('delete_entry') }}">Delete</a>
{% endif %}
{% else %}
{% endfor %}
</ul>
As you can see, next to each entry there’s a delete link.How am I supposed to reference the
right id in the database?
Here’s the Python function I have so far:
@app.route('/delete')
def delete_entry():
if not session.get('logged_in'):
abort(401)
g.db.execute('delete from entries where id=(select max(id)from entries)')
g.db.commit()
flash('The entry was deleted')
return redirect(url_for('show_entries'))
What I have so far works but It’s not what I want. Thanks in advance!
Sebastien the delete_entry function is deleting the last entry in the db
where id=(select max(id)from entries)What you have to do is insert a parameter in the url for deletion like ‘/delete/:id’ where the id is the id of the entry you want deleted, then change the template to generate the url as so:
And also change the db query that deletes the entry:
Edit1:
I checked the Flask documentation, in order to get variables into your routes you have to modify the route as follows:
In this way you obtain the entry_id in your python function:
And finally you have to specify your entry id in the url_for function: