记住选定的下拉菜单值 Python/Flask

4
            <option value="1" {{ selected }}>1</option>
            <option value="2" {{ selected }}>2</option>
            <option value="3" {{ selected }}>3</option>
            <option value="4" {{ selected }}>4</option>

我有一个涉及几个下拉菜单的Flask应用程序。我希望当用户提交表单时传递所选值,以便在下一页上看到他们的先前选择。
请问是否可以提供一个简单的实例?我无法构思如何实现这一点。
谢谢。
1个回答

6

Python Flask 视图

@app.route('/form/')
def form():
    # list of tuples representing select options
    choices = [(str(x), str(x)) for x in range(1, 20)]
    # test if value was passed in (e.g. GET method), default value is 1
    selected = request.args.get('choice', '1')
    # application 'state' variable with default value and test
    state = {'choice': selected}
    return render_template('view_form.html', choices=choices, state=state)

在Jinja模板中:

{% for row in choices %}
<option value="{{ row[0] }}"{% if row[0] == state.choice %} selected{% endif %}>{{ row[1] }}</option>
{% endfor %}

我尝试了这个,当我选择任何选项并提交表单后,下一页会将选择重置为1。 - D3l_Gato
1
当更改以下内容时,它可以正常工作:selected = str((request.form['choz'])) #selected = request.args.get('choice', '1') - D3l_Gato
@abigperson 我在使用Flask和Python时遇到了下拉菜单的问题,能帮我解决一下吗?链接在这里:https://stackoverflow.com/questions/49628274/unable-to-get-value-selected-in-python-from-a-dropdown-using-flask - Tia

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接