Django ModelForm float field not calling Clean_Field method
Asked Answered
I

1

7

i am having a unique kind of problem. i am putting "$90" value in my floatField. i assume it should be cleaned and stored as "90.0" in the model.

but when i input "$90" and call clean_filed method, it does not call that clean method. but when i apply the breakpoint on clean(self) mehthod and try to get its value, its says None.

please help me out. here is my code.

Model
class Project(models.Model):
foo = models.FloatField("foo",
        null=True, blank=True
    )


forms
widgets = {
         'foo': forms.TextInput(attrs={'currency': 'true'})}

    def clean_foo(self):
        value = self.cleaned_data.get('foo')
        print value # i get NONE here.............
        return value 
Ignominious answered 30/9, 2013 at 12:49 Comment(1)
Have you tried other inputs? Like "90" without the "$" sign or an already clean "90.0"? Try seeing if it's really a problem with the cleaning and not something elseNirvana
L
19

The clean_<field> hooks in the forms API are for doing additional validation. It is called after the field calls its clean method. If the field does not consider the input valid then the clean_<field> is not called. This is noted in the custom validation docs https://docs.djangoproject.com/en/stable/ref/forms/validation/

For any field, if the Field.clean() method raises a ValidationError, any field-specific cleaning method is not called. However, the cleaning methods for all remaining fields are still executed.

In your case because $90 does not validate as a float it will not be called. Instead what you should do is create a subclass of the FloatField which cleans the input (removing $, etc) prior to validating the input as a float.

Licha answered 30/9, 2013 at 13:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.