ValueError无法将字符串转换为浮点:“”

2024-04-24 13:16:44 发布

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

我的应用程序在heroku上。 我使用timeme js记录用户在页面上的活动时间,并使用隐藏表单将值存储到数据库中。此外,我正在使用otree软件包编写我的应用程序。 以下是我使用的代码:

models.py

class Active(ExtraModel):
    active_duration = models.FloatField()
    active_record = models.LongStringField()

otree中的views.py/pages.py

class 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>

错误

ValueError
could not convert string to float: ''

{
  "csrfmiddlewaretoken": "vVhVRLrAUokmiNGRpzCaP78bnTOQyowf5VMfIDgKGglWGuEyQAU2wooWjQzXuBgD",
  "active_duration": "",
  "active_record": ""
}

是因为活动持续时间为空吗?如果我为表单设置blank=true,null=true,会有帮助吗

我假设每次使用都会对输入有价值。还有关于为什么输入为空的想法吗?是否用户使用脚本跳过没有可见字段的页面?从sentry错误消息中,这两次发生在一个用户身上


Tags: 用户pyselfformid应用程序表单data
1条回答
网友
1楼 · 发布于 2024-04-24 13:16:44

这是因为不能将空字符串强制转换为浮点。不过,您可以这样做:

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

如果数据[“活动\u持续时间”]为空、假或无,则会给您一个“0”

>>> data = {"foo": ""}
>>> data.get("foo") or "bar"
'bar'

相关问题 更多 >