Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/315.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 具有选择选项在使用烧瓶后保持选中状态_Python_Html_Select_Flask_Jinja2 - Fatal编程技术网

Python 具有选择选项在使用烧瓶后保持选中状态

Python 具有选择选项在使用烧瓶后保持选中状态,python,html,select,flask,jinja2,Python,Html,Select,Flask,Jinja2,我正在尝试获取一个选择选项,该选项在使用Flask刷新页面后被选中。我曾尝试使用Jinga2,但它不起作用: 福 酒吧 其中变量energy被填充并通过Python传递。经过研究,我觉得这是在烧瓶中工作的方法,虽然显然不是。任何帮助都将不胜感激 @应用程序,路由'/things',方法=['POST'] 定义事物 如果lenfacts['thing']>11: 能量=[facts['thing'][0:8],facts['thing'][9:] 其他: 能量=[事实[事物]] ... 返回ren

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

福 酒吧 其中变量energy被填充并通过Python传递。经过研究,我觉得这是在烧瓶中工作的方法,虽然显然不是。任何帮助都将不胜感激

@应用程序,路由'/things',方法=['POST'] 定义事物 如果lenfacts['thing']>11: 能量=[facts['thing'][0:8],facts['thing'][9:] 其他: 能量=[事实[事物]] ... 返回render_模板'thing.html',thing=energy
请查看此示例,因为它适用于您尝试执行的操作。我无法准确地调试代码中的错误,因为您向我提供了部分,而我不知道它们在做什么

文件夹结构

things.html


如果你还没有尝试过,试试这个

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

重要的部分是使用所需选项中的选定项呈现页面:

<option value="Foo" selected>Foo</option>
double_j关于使用模板将其插入html的回答非常有效,但是如果您从列表中构建下拉列表,那么从python构建html可能会更容易:


你能在上面贴一个服务器端流代码的例子吗。当您说刷新时,我假设这意味着用户只是刷新页面,页面应该发送GET请求。这样就不会在表单中发布任何信息,所以我不知道你是如何保存变量的。我说错了,而不是像我在发布时所说的那样使用“刷新”。我用Python/Flask编辑了这个问题,以及我如何存储和传递该变量。谢谢兄弟:-
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)
{% 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 %}
<option value="Foo" selected>Foo</option>
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)