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

Flask中request.form.get获取select值始终为None问题排查

Flask表单无法获取select值的问题排查与修复

核心问题1:表单缺少提交按钮

你的tellmestory.html表单里没有提交按钮,用户无法触发表单提交操作,导致/story路由接收不到任何表单数据,request.form.get('child_age')自然返回None。

核心问题2:默认选项的处理(可选但重要)

默认的<option disabled selected>没有设置value,且disabled状态的选项不会被提交。如果用户未选择任何年龄直接提交(即使有提交按钮),依然会出现child_age为None的情况。

修改后的代码示例

1. tellmestory.html 添加提交按钮并优化默认选项

<form action="/story" method="post">
    <div class="form-group justify-content-center">
        <label for="child_age">Select child's age:</label>
        <select id="child_age" class="form-select" name="child_age" aria-label="Select child's age">
            <!-- 给默认选项添加空value,方便后端判断是否未选择 -->
            <option value="" selected>Select child's age</option>
            {% for child_age in age%}
                <option value="{{ child_age }}">{{ child_age }}</option>
            {% endfor %}
        </select>
    </div>
    <!-- 添加提交按钮,触发表单提交 -->
    <div class="mt-3">
        <button type="submit" class="btn btn-primary">生成故事</button>
    </div>
</form>

2. app.py 中添加基础表单验证(可选)

可以在/story路由里判断是否获取到有效数据,避免返回None:

from flask import redirect, url_for

# 保留原有的AGE定义和tellmestory路由

@app.route("/story", methods=["POST"])
def story():
    child_age = request.form.get("child_age")
    # 如果未选择年龄,重定向回选择页面
    if not child_age:
        return redirect(url_for('tellmestory'))
    return render_template("story.html", child_age=child_age)

内容的提问来源于stack exchange,提问作者Gabriela Cocoș

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 06:02:09