Skip to content
Advertisement

ValueError could not convert string to float: ”

I’m having my app on heroku. I use timeme js to record user’s active time spend on the page, and use a hidden form to store the value into the database. Additionally, I’m using otree package to write my app. The following is the code I use:

models.py

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

views.py/pages.py in otree

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>

The error

ValueError
could not convert string to float: ''

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

Is it because active_duration is empty? Will it help if I set blank=true, null=true for the forms?

I was assuming that every use would have value for the input. Also any ideas about why the input is empty? Could it be that the user used scripts to skip the page without visible fields? From the sentry error message, this happened to one user twice.

Advertisement

Answer

It is because you cannot cast an empty string to a float. You can do this instead though:

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

This will give you a “0” if data[“active_duration”] is empty, False, or None.

>>> data = {"foo": ""}
>>> data.get("foo") or "bar"
'bar'
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement