将复选框值发送到flas

2024-04-24 20:55:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个表格是这样的:

<form id="settings" action="{{ url_for("load_settings") }}" method="post">
... 

    <label for="m_r">Interval 1</label>
    <input type="text" name="morn_r" id="m_r">

    <label for="d1_e">Enabled</label>
    <input type="checkbox" name="d_enabled" id="d1_e" value="off" onclick="toggle_check(this)">
</form>

这是toggle_check函数:

^{pr2}$

这是我的Python:

@app.route("/settings", methods=["POST", "GET"])
def load_settings():
    if request.method == "POST":
        settings = list(request.form.values())
        print(settings)
    return render_template("settings.html")

如果我将文本输入保留为空,但单击复选框,则打印内容如下:[..., '', 'on']

现在,如果我将复选框留空,那么打印的内容是:[..., '']。由于某些原因,它没有添加复选框的值。。。在

我不知道怎么解决这个问题。有人能帮忙吗?在

谢谢。在


Tags: nameformidforinputsettingschecktype
1条回答
网友
1楼 · 发布于 2024-04-24 20:55:29

this answer窃取,HTML 4 recommendation from W3C声明:

Checkboxes (and radio buttons) are on/off switches that may be toggled by the user. A switch is "on" when the control element's checked attribute is set. When a form is submitted, only "on" checkbox controls can become successful.

因此,这与Flask无关,为什么复选框值在未选中时不在那里。当复选框被取消选中时,浏览器不会将表单输入序列化到请求中。在

但是,您可以在模板中为输入提供一些合理的值:

<input type="checkbox" name="d_enabled" value="on">

然后在烧瓶处理程序中检查是否存在该值:

^{pr2}$

相关问题 更多 >