记住选定的下拉值Python / Flask

时间:2016-12-18 18:35:10

标签: html python-2.7 flask

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

我有一个带有一些下拉菜单的烧瓶应用程序。我想在用户提交表单时传递所选值,以便他们在下一页上看到他们之前的选择。

有人可以提供一个简单的例子吗?我只是无法概念化如何实现这一目标。

由于

1 个答案:

答案 0 :(得分:4)

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