You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flask(Jinja)下拉框保留上次选中项问题求助

Flask下拉框提交后无法保留选中值问题

在Flask的screener功能中,选择国家提交表单后,下拉框无法保留上次选中的国家,始终显示“Any”(已确认country变量已传递到模板)。下拉选项示例:id=1对应'France',id=2对应'Japan',希望选择日本(id=2)后,下拉框能显示日本而非“Any”。相关代码如下:

screener.html

<form method=POST action="{{ url_for('screener') }}" onchange=submit()>
  <table class="table table-sm table-hover">
    <thead>
    <tr><td>control : {{ country }}</td></tr>
    <tr>
        <td>Country</td>
        <td>
          <select id="country" name="country" class="form-select form-select-sm" aria-label="">
            <option value="">Any</option>
            {% for db_country in db_countries %}
              <option value="{{ db_country.id }}" {% if country == db_country.id %} selected {% endif %} >
                {{ db_country.id }} - {{ db_country.name }}</option>
            {% endfor %}
          </select>
        </td>
    </tr>
    <tr>
  </table>
</form>

app.py

@app.route('/screener/', methods=['POST', 'GET'])
def screener():
    db_countries = Country.query.order_by(Country.name.asc()).all()
    if request.method == 'POST':
        country = request.form['country']
    else:
        country = 0
    return render_template('screener.html', title='Screener',db_countries=db_countries, country=country)

问题原因

核心是类型不匹配:

  • 表单提交的country值是字符串类型(比如"2")
  • db_country.id是整数类型(比如2)
  • 模板中{% if country == db_country.id %}的对比是字符串与整数比较,结果永远为False,导致选中状态无法生效
  • 初始值country = 0(整数)和"Any"选项的value=""(空字符串)也不匹配,初始状态逻辑也有问题

修复方案

方案1:后端统一变量类型

修改app.py,将表单值转为整数,同时把初始值设为空字符串,匹配"Any"选项的value:

@app.route('/screener/', methods=['POST', 'GET'])
def screener():
    db_countries = Country.query.order_by(Country.name.asc()).all()
    if request.method == 'POST':
        country = request.form.get('country', '')
        # 把字符串转为整数,非数字值设为空字符串
        country = int(country) if country.isdigit() else ''
    else:
        # 初始值设为空字符串,对应"Any"选项
        country = ''
    return render_template('screener.html', title='Screener', db_countries=db_countries, country=country)

方案2:模板中转换类型对比

如果不想修改后端逻辑,可在模板中将db_country.id转为字符串后比较:

<option value="{{ db_country.id }}" {% if country == str(db_country.id) %} selected {% endif %} >
  {{ db_country.id }} - {{ db_country.name }}
</option>

修复后,提交表单时下拉框会正确保留选中的国家,初始状态也会默认显示“Any”。

内容的提问来源于stack exchange,提问作者Nuno

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 03:15:46