2017-04-20 50 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 %}