为了账号安全,请及时绑定邮箱和手机立即绑定

ValueError 无法将字符串转换为浮点数:''

ValueError 无法将字符串转换为浮点数:''

斯蒂芬大帝 2023-12-26 14:56:06
我在 heroku 上安装了我的应用程序。我使用timeme js记录用户在页面上花费的活跃时间,并使用隐藏表单将值存储到数据库中。此外,我正在使用 otree 包来编写我的应用程序。以下是我使用的代码:models.pyclass Active(ExtraModel):    active_duration = models.FloatField()    active_record = models.LongStringField()otree 中的views.py/pages.pyclass intro_instructions(Page):    def before_next_page(self):        data = self.form.data        p = self.player        active = Active.objects.create(active_duration=data['active_duration'],                                       active_record=data['active_record'])        active.save()html<form method="post" role="form" id="form" autocomplete="off">{% csrf_token %}    <input type="text" name="active_record" id="id_active_record" style="display: none" >    <input type="number" step='any' name="active_duration" id="id_active_duration" style="display: none"></form>错误ValueErrorcould not convert string to float: ''{  "csrfmiddlewaretoken": "vVhVRLrAUokmiNGRpzCaP78bnTOQyowf5VMfIDgKGglWGuEyQAU2wooWjQzXuBgD",  "active_duration": "",  "active_record": ""}是因为 active_duration 为空吗?如果我为表单设置 Blank=true, null=true 会有帮助吗?我假设每次使用都会有输入价值。还有关于为什么输入为空的任何想法吗?难道是用户使用脚本跳过了没有可见字段的页面?从哨兵错误消息来看,一名用户发生了两次这种情况。
查看完整描述

1 回答

?
qq_花开花谢_0

TA贡献1835条经验 获得超6个赞

这是因为你不能将空字符串转换为浮点数。不过你可以这样做:


active_duration=data.get('active_duration') or "0"

如果 data["active_duration"] 为空、False 或 None,这将为您提供“0”。


>>> data = {"foo": ""}

>>> data.get("foo") or "bar"

'bar'


查看完整回答
反对 回复 2023-12-26
  • 1 回答
  • 0 关注
  • 50 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信