How do I get my HTML button to delete the right list item from a SQLite database?
Just add a hidden input to every form with the element id/name that you want to delete as the value :)
eg.
<form action="{{ url_for('delete_movie') }}" method=post class=delete-movie>
<input type=hidden value="{{ movie.name }}"name=movie_to_delete />
<input type=submit />
</form>
IMO, the method in above answer is quite unnecessary. You should pass the movie's name as URL variable:
{% for movie in movies %}
<li><h1>{{ movie.title }}</h1>
<form action="{{ url_for('delete_movie', movie_name=movie.name) }}" method=post>
<input type=submit value=Delete">
</form>
{% endfor %}
In view function, include the variable in URL rule (i.e. /delete/<movie_name>
), then you can get the movie's name as a parameter:
@app.route('/delete/<movie_name>', methods=['POST'])
def delete_movie(movie_name):
g.db.execute('delete from movies where movie = ?', [movie_name])
...
However, in this use case, people normally pass the id value of movie record instead of the name. Here is a minimal example from a similar application:
Template:
<form method="post" action="{{ url_for('delete_movie', movie_id=movie.id) }}">
<input class="btn" type="submit" name="delete" value="Delete">
</form>
View:
@app.route('/movie/delete/<int:movie_id>', methods=['POST'])
@login_required
def delete_movie(movie_id):
movie = Movie.query.get_or_404(movie_id)
db.session.delete(movie)
db.session.commit()
flash('Item deleted.')
return redirect(url_for('index'))