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

如何将HTML下拉列表选中值提交至FastAPI后端?

解决HTML下拉菜单值提交到FastAPI后端的问题

问题场景

使用FastAPI配合Jinja2模板开发时,前端HTML下拉菜单选中的值无法提交到后端,提交后返回错误:

{"detail":[{"loc":["body","result"],"msg":"field required","type":"value_error.missing"}]}

目标是实现选择下拉选项后点击提交,页面下方显示选中的对应值。

错误原因

后端POST接口接收表单数据的Form参数名为result,但前端<select>标签的name属性是names,两者名称不匹配,导致FastAPI无法找到对应字段,触发必填字段缺失的错误。

修复步骤

1. 修改FastAPI后端代码

将POST接口的Form参数名改为和前端select的name一致的names,然后将该参数值传递给模板的result变量:

from fastapi import FastAPI, Request, Form
from fastapi.templating import Jinja2Templates

app = FastAPI()
templates = Jinja2Templates(directory="templates/")


@app.get('/')
def read_form():
    return 'hello world'


@app.get("/form")
def form_post(request: Request):
    result = "Select your name"
    return templates.TemplateResponse('form.html', context={'request': request, 'result': result})


@app.post("/form")
# 将参数名从result改为names,和前端select的name对应
def form_post(request: Request, names: str = Form(...)):
    return templates.TemplateResponse('form.html', context={'request': request, 'result': names})

2. 前端模板优化(可选)

给下拉菜单添加默认提示选项,提升用户体验:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Sample Form</title>
</head>
<body>
<form method="post">
    <select name="names" id="names">
        <!-- 添加默认禁用的提示选项 -->
        <option value="" selected disabled>请选择姓名</option>
        <option value="n1">Name 1</option>
        <option value="n2">Name 2</option>
        <option value="n3">Name 3</option>
        <option value="n5">Name 4</option>
    </select>
    <input type="submit" value="Submit">
</form>
    
<p>Result: {{ result }}</p>

</body>
</html>

验证结果

启动FastAPI服务后,访问/form页面,选择下拉选项并点击提交,页面下方的Result区域会显示选中的对应值(如n1、n2等)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 06:31:09