【问题标题】:Having a select option stay selected after POST with Flask使用 Flask POST 后选择选项保持选中状态
【发布时间】:2017-09-17 15:01:32
【问题描述】:

我正在尝试获取一个选择选项,该选项在使用 Flask 刷新页面后被选中。我曾尝试使用 Jinga2 这样做,但它不起作用:

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

变量energy 被填充并通过Python 传递。在研究了这个之后,我觉得这是在 Flask 中进行这项工作的方法,尽管显然不是。任何帮助将不胜感激!

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

【问题讨论】:

  • 您能否在此发布您的服务器端流程代码示例。当你说“刷新”时,我认为这意味着用户只是刷新页面,它应该发送一个 GET 请求。所以这不会通过表单发布任何信息,所以我不知道你是如何保存变量的。
  • 我误会了在 POST 发生时使用刷新这个词的意思。我用我的 Python/Flask 编辑了这个问题,以及我如何存储和传递该变量。

标签: python html select flask jinja2


【解决方案1】:

请查看此示例,因为它适用于您尝试执行的操作。我无法准确调试您的代码中出了什么问题,因为您向我提供了部件,但我不知道他们在做什么。

文件夹结构

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)

【讨论】:

    【解决方案2】:

    重要的部分是在您想要的选项中使用selected 呈现页面:

    <option value="Foo" selected>Foo</option>
    

    double_j's answer to use templates to insert it into your html's answer of using templates to insert it into your html 效果很好,但如果你从列表中构建下拉列表,从 python 构建你的 html 可能会更容易:

    import flask
    import socket
    
    app = flask.Flask(__name__)
    
    all_things = ['Foo', 'Bar', 'Fizz', 'Buzz']
    current_thing = None
    def show_selection(target):
        if target == current_thing:
            return 'selected'
        else:
            return ''
    
    def menu():
        template = '''<form action = "things" method = "post">
        <select id="target" name="target">
        {targets}
        </select>
        <input type="submit" name="build" value="Build">
    </form>
        '''
        # vvv This is the important part vvv
        targets = [f'<option value="{t}" {show_selection(t)}>{t}</option>' for t in all_things] 
        return template.format(
            targets='\n'.join(targets)
        )
        # ^^^ This is the important part ^^^
    
    @app.route('/things', methods=['GET', 'POST'])
    def things():
        global current_thing
        current_thing = flask.request.form.get('target')
        page = menu()
        if flask.request.method == 'POST' and 'build' in flask.request.form:
            page += f'Building {current_thing}'
        else:
            page += 'Press Build button'
        return page
    
    
    if __name__ == '__main__':
        PORT = 8080
        print("Visit http://{}:{} to trigger builds".format(socket.gethostname(), PORT))
        app.run(host='0.0.0.0', port=PORT, debug=True)
    
    

    【讨论】:

      【解决方案3】:

      试试这个,如果你还没有的话

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

      【讨论】:

        猜你喜欢
        • 2014-06-14
        • 1970-01-01
        • 2018-10-24
        • 2016-07-13
        • 1970-01-01
        • 2012-08-07
        • 2013-07-23
        • 1970-01-01
        • 2019-04-16
        相关资源
        最近更新 更多