2013-09-28 123 views
3

我目前的項目,我的索引頁面顯示了幾個種子,每個種子都有一個按鈕,用於啓動或停止洪流。如何知道我在燒瓶中點擊了哪個按鈕?

我使用窗體和循環創建頁面,因此窗體始終具有相同的名稱。但我需要知道用戶點擊了哪個按鈕才能知道哪個torrent停止!

這裏是模板:

{% 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 %} 

這裏是視圖:

@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) 

所以,我怎麼知道哪個洪流用戶想要停止/啓動?

+0

我們可以看到'hidden_​​tag'的代碼嗎? –

+0

托馬斯是正確的,因爲你打開一個表格每個洪流整個問題是真的不存在,因爲你可以簡單地提交信息哈希在一個隱藏的領域。我的答案假設整個頁面或列表的單一表單。 – jhermann

回答

0

使用HTML <button type="submit">元素並將value設置爲信息散列,或設置包含信息散列的formaction URL(formaction僅爲HTML5)。

2

假設hidden_tag創建hidden輸入名稱爲torrent_id和價值洪流的ID,你會發現洪流ID在request.form["torrent_id"]

from flask import request 

.... 
torrent_id = request.form["torrent_id"] 
+0

hidden_​​tag只是一個csrf保護標記。但我會嘗試使用你的建議。 – 22decembre

+0

@ 22decembre只需用''替換'a',你就會很好。 –

+0

好的,這解決了「哪個按鈕被點擊」的問題,順便說一下,我瞭解了我不知道的按鈕(我知道輸入,而不是按鈕)。 但是現在出現這樣一個事實,即我得到儘可能多的答案,因爲我已經因爲循環而內聯了!那麼我如何才能啓動一次函數呢? – 22decembre

0

托馬斯給出了正確的答案!

現在來了一個事實,即我得到儘可能多的答案,因爲我有內聯,因爲循環!那麼我如何才能啓動一次函數呢?

我知道這聽起來很愚蠢,但讓我們說我沒有看到它!

+0

通過將'if torrent.control.validate_on_submit'退出循環解決。 – 22decembre

相關問題