How to know which button I clicked in flask?
10,347
Assuming hidden_tag
creates a hidden
input with name torrent_id
and value the ID of the torrent, you will find the torrent id in request.form["torrent_id"]
:
from flask import request
....
torrent_id = request.form["torrent_id"]
Author by
22decembre
Updated on June 20, 2022Comments
-
22decembre almost 2 years
I my current project, my index page show several torrents with a button for each to start or stop the torrent.
I create the page with a form and a loop, so the forms have always the same names. But I need to know which button the user has clicked to know which torrent to stop !
Here is the template :
{% block content %} <h1>Hello, {{user}} !</h1> {% for torrent in torrents %} <form action="/index" method="post" name="torrent"> {{torrent.control.hidden_tag()}} <p><a href='/torrent/{{torrent.id}}'>{{torrent.name}}</a> is {{torrent.status}} and {{torrent.progress}} % finished. <input type="submit" value="Start / Stop"> </p> </form> {% endfor %}
Here is the view :
@app.route('/index', methods = ['GET', 'POST']) def index(): user = 'stephane' torrents = client.get_torrents() # for each torrent, we include a form which will allow start or stop for torrent in torrents: torrent.control = TorrentStartStop() if torrent.control.validate_on_submit(): start_stop(torrent.id) return render_template("index.html", title = "Home", user = user, torrents = torrents)
So, how do I know which torrent the user want to stop/start ?
-
22decembre over 10 yearsThe hidden_tag is just a csrf protection tag. But I will try something using your advice.
-
Thomas Orozco over 10 years@22decembre Just replace the
a
with<input type="submit" name="torrent_id" value="{{ torrent.id }}"/>
and you'll be good. -
22decembre over 10 yearsOk, so this solved the "which button is clicked" problem, and by the way, I learn about the button I didn't know (I knew the input, not the button). But now comes the fact that I get as many answer as I have torrents inline because of the loop ! So how do I launch the function only one time ?