如何通过FastAPI与Jinja2 Templates提交HTML表单<input>值至路径参数?
问题:HTML表单输入值无法通过路径参数传递到FastAPI端点
我在尝试将HTML表单<input>元素的值传递到表单的action属性并发送至FastAPI服务器时遇到问题,以下是我的实现细节:
FastAPI模板加载代码
# Test TEMPLATES @app.get("/test",response_class=HTMLResponse) async def read_item(request: Request): return templates.TemplateResponse("index.html", {"request": request})
HTML表单代码
<form action="/disableSubCategory/{{subCatName}}"> <label for="subCatName">SubCategory:</label><br> <input type="text" id="subCatName" name="subCatName" value=""><br> <input type="submit" value="Disable"> </form>
FastAPI端点代码
# Disable SubCategory @app.get("/disableSubCategory/{subCatName}") async def deactivateSubCategory(subCatName: str): disableSubCategory(subCatName) return {"message": "SubCategory [" + subCatName + "] Disabled"}
出现的错误
"GET /disableSubCategory/?subCatName=Barber HTTP/1.1" 404 Not Found
期望的调用形式
我希望提交表单后,请求路径是:
/disableSubCategory/Barber
问题原因
- HTML的GET表单默认会把输入字段以查询参数(
?key=value)的形式附加到action指定的URL后,但你的FastAPI端点期望的是路径参数(/path/value),两者不匹配导致404。 - 表单里的
{{subCatName}}是Jinja2模板变量,但渲染模板时并没有传入这个变量,所以实际渲染后的action是/disableSubCategory/,提交时输入值会自动转为查询参数。
解决方法
方法1:用JavaScript动态修改表单action(推荐,符合路径参数需求)
在表单提交前,获取输入框的值,动态替换action路径,确保输入值作为路径参数传递:
<form id="disableForm" action="/disableSubCategory/"> <label for="subCatName">SubCategory:</label><br> <input type="text" id="subCatName" name="subCatName" value=""><br> <input type="submit" value="Disable"> </form> <script> document.getElementById('disableForm').addEventListener('submit', function(e) { const subCatName = document.getElementById('subCatName').value.trim(); if (subCatName) { this.action = `/disableSubCategory/${subCatName}`; } else { e.preventDefault(); // 空值时阻止提交,避免无效请求 alert('请输入子分类名称'); } }); </script>
方法2:修改FastAPI端点接收查询参数
如果业务上允许用查询参数传递值,只需修改端点代码,将路径参数改为查询参数即可:
# Disable SubCategory @app.get("/disableSubCategory") async def deactivateSubCategory(subCatName: str): disableSubCategory(subCatName) return {"message": "SubCategory [" + subCatName + "] Disabled"}
这种方式不需要修改HTML表单,提交后请求会是/disableSubCategory?subCatName=Barber,端点能正常处理返回结果。
内容的提问来源于stack exchange,提问作者Leonardo Lopes
相关产品推荐
相关产品推荐

