2017-04-20 55 views
0

我試圖得到一個選擇選項,以保留頁面刷新後,並試圖與Jinga2這樣做,雖然我覺得應該工作是行不通的。有一個選擇選項保持選中POST後使用Flask

<div class="col-sm-4 col-lg-4 col-md-4"> 
       <select class="form-control" id="myselect" name="thing" required> 
         <option value="" {% if thing=='' %} selected {% endif %} ></option> 
         <option value = "Foo" name ="Foo" id="Foo" {% if thing =="Foo" %} selected {% endif %} >Foo</option> 
         <option value = "Bar" name ="Bar" id="Bar" {% if thing =='Bar' %} selected {% endif %}>Bar</option> 
       </select> 
</div> 

可變能量填充並通過Python傳遞的地方。仔細研究之後,我覺得這是Flask的工作方式/語法,儘管顯然不是。任何援助將不勝感激!

編輯: 的Python /瓶

@app,route('/things', methods=['POST'] 
def things() 
    if len(facts['thing']) > 11: 
     energy = [facts['thing'][0:8],facts['thing'][9:]] 
    else: 
     energy = [facts['things']] 
.... 
return render_template('thing.html, thing=thing) 
+0

你可以發佈一個你的服務器端流程代碼的例子。當你說「刷新」時,我認爲這意味着用戶只是刷新頁面,應該發送一個GET請求。所以這不會通過表單發佈任何信息,所以我不知道如何保存變量。 –

+0

我比在POST發生時使用「刷新」這個詞意味着錯誤。我用我的Python/Flask編輯了這個問題,以及我如何存儲和傳遞該變量。 – MVS

回答

0

請參閱此例子,因爲它適用於你想要做什麼。我無法準確地調試代碼中出了什麼問題,因爲您向我提供了部分代碼,我不知道他們在做什麼。

文件夾結構

Test 
|___templates 
| |___things.html 
|___Test.py 

things.html

<form method="post"> 
    <div class="col-sm-4 col-lg-4 col-md-4"> 
     <select title="thing" class="form-control" id="myselect" name="thing" required> 
      <option value="" {% if thing=='' %} selected {% endif %} ></option> 
      <option value="Foo" name="Foo" id="Foo" {% if thing =="Foo" %} selected {% endif %} >Foo</option> 
      <option value="Bar" name="Bar" id="Bar" {% if thing =='Bar' %} selected {% endif %}>Bar</option> 
     </select> 
     <button type="submit">SEND</button> 
    </div> 
</form> 

Test.py

from flask import Flask, render_template, request 

app = Flask(__name__) 
PORT = 5000 


@app.route('/things', methods=['GET', 'POST']) 
def things(): 
    """ 
    Accepts both GET and POST requests. If it's a GET request, 
    you wouldn't have a last selected thing, so it's set to an 
    empty string. If it's a POST request, we fetch the selected 
    thing and return the same template with the pre-selected 
    thing. 
    You can improve on this and save the last selected thing 
    into the session data and attempt to retrieve it from there. 
    """ 
    thing = '' 
    if request.method == 'GET': 
     return render_template('things.html', thing=thing) 
    else: 
     thing = request.form.get('thing', '') 
     return render_template('things.html', thing=thing) 


if __name__ == '__main__': 
    app.run(port=PORT) 
0

試試這個,如果你有還不是

{% if thing == "Foo" %} 
    <option value = "Foo" name ="Foo" id="Foo" selected>Foo</option> 
    <option value = "Bar" name ="Bar" id="Bar">Bar</option> 
{% elif thing == "Bar" %} 
    <option value = "Foo" name ="Foo" id="Foo">Foo</option> 
    <option value = "Bar" name ="Bar" id="Bar" selected>Bar</option> 
{% endif %}