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

HTML表单datetime-local值提交到Flask返回NoneType问题求助

故障根因
  • HTML代码中两个datetime-local类型的input标签,type和name属性之间多写了多余的英文逗号,浏览器无法正常识别name属性,导致表单提交时没有携带对应字段,Flask读取不到值就返回None。
修复步骤

1. 修正HTML表单代码

删除input标签属性间的多余逗号即可,修正后的完整代码如下:

<form action="/" method="POST">
    <div style="font-size:15px; font-weight:bold; margin-left:150px;">
        <p>start<br><input type="datetime-local" name="time_start" required></p>
        <p>end<br><input type="datetime-local" name="time_end" required></p>
        <p><input type="submit" value="submit"></p>
    </div>
</form>

这里额外给style属性加了引号,修正了拼写错误的mergin为margin,添加了required属性避免用户未选择时间直接提交。

2. 验证Flask获取逻辑

原Flask逻辑无需修改,提交表单后就可以正常拿到时间字符串,输出格式为YYYY-MM-DDTHH:MM,如果需要转换为Python的datetime对象,可以按以下方式处理:

from datetime import datetime
from flask import Flask, request

app = Flask(__name__)

@app.route('/',methods=["GET","POST"])
def hello_world():
    if request.method == "POST":
        st=request.form.get("time_start")
        ed=request.form.get("time_end")
        # 字符串转datetime对象
        if st and ed:
            st_dt = datetime.fromisoformat(st)
            ed_dt = datetime.fromisoformat(ed)
            print(st_dt, type(st_dt))
            print(ed_dt, type(ed_dt))
    return "ok"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 19:45:03