How to delete record in Sqlite


Question

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!

1
2
11/1/2011 2:42:08 PM

Accepted Answer

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:

<a href="{{ url_for('delete_entry', entry.id) }}">Delete</a>

And also change the db query that deletes the entry:

g.db.execute('delete from entries where id=' + id)

Edit1:

I checked the Flask documentation, in order to get variables into your routes you have to modify the route as follows:

@app.route('/delete/<int:entry_id>')

In this way you obtain the entry_id in your python function:

def delete_entry(entry_id):
g.db.execute('delete from entries where id=' + entry_id)

And finally you have to specify your entry id in the url_for function:

<a href="{{ url_for('delete_entry', entry_id = entry.id) }}">Delete</a>
5
11/1/2011 3:02:49 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon