Opened 5 years ago

Closed 5 years ago

#31084 closed Cleanup/optimization (invalid)

ValueError: could not convert string to float.

Reported by: Sevdimali Owned by: nobody
Component: Database layer (models, ORM) Version: 2.2
Severity: Normal Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

Hi,
I have a field like this(models.py):

value = models.FloatField(null=True)

And I have a simple form (template/form.html)

 <form action="{% url 'submit_form' %}" method="post">
    {% csrf_token %}
    <input type="hidden" name="star" value="">
    <input type="submit">
</form>

in my view, I am saving this form (views.py) :

 def submit_form(request):
    if request.method == "POST":
        print("aa")
        score = request.POST.get('star')
       
        simpleform.objects.create(
            value=score,
        )
    return redirect("/form")

and of course, I am getting this exception:

ValueError: could not convert string to float:


Adding if statement something like this to view will solve the exception:

   if len(score) == 0:
            score = None

I am thinking that maybe we can add this check to our site-packages/django/db/fields/init.py

    def get_prep_value(self, value):
        value = super().get_prep_value(value)
        if value is None:
            return None
        return float(value)

to

 def get_prep_value(self, value):
        value = super().get_prep_value(value)
        if value is None or len(value) == 0:
            return None
        return float(value)

Change History (1)

comment:1 by Mariusz Felisiak, 5 years ago

Component: UncategorizedDatabase layer (models, ORM)
Resolution: invalid
Status: newclosed
Summary: ValueError: could not convert string to float:ValueError: could not convert string to float.

You're trying to use a raw value from POST to create a new model instance, in general that's not a proper way to do this. Please don't use Trac as a support channel.

Closing per TicketClosingReasons/UseSupportChannels.

Note: See TracTickets for help on using tickets.
Back to Top