Fastapi 表单数据来自 Bootstrap 5 开关盒

Fastapi form data from Bootstrap 5 Switch box

我想使用 Bootstrap 5:

的开关盒
<div class="form-check form-switch">
        <input class="form-check-input" type="checkbox" name="yes_no" id="flexSwitchCheckDefault">
        <label class="form-check-label" for="flexSwitchCheckDefault">Yes</label>
</div>

切换按钮为'On'或True时有效,但当它为'Off'时,我在控制台中收到以下错误:

"?[1mPOST /form HTTP/1.1?[0m" ?[31m422 Unprocessable Entity?[0m

在前端:

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

尝试在 Python 中使用 if/else 语句:

@app.post("/form")
def form_post(request: Request,
              yes_no: bool = Form(...)):
    if yes_no:
        print(yes_no)
    else:
        print("No")
    return templates.TemplateResponse("form_response.html", 
                                      context={'request':request}

但我仍然得到同样的错误。我也试过其他东西,比如 yes_no:str = Form(...) 但仍然是同样的错误。

我想要的输出是值 'Yes' 如果切换是 'On' 或 True 和值 'No' 如果值是 'Off' 或False.

如果您希望该值是可选的,请提供默认值:

@app.post("/form")
def form_post(request: Request,
              yes_no: bool = Form(False)):