Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Flask WTForms FloatField allow 1,0 and 1.0 allow comma and dot

I have a flask app where a user can submit a room. There is a price field which is a FloatField in my WTForms:

preis = FloatField('Preis p.P.', validators=[Optional()])

If the input is correct (with a dot) it works fine, example:

1.00

But if a comma is used it triggers an error, example:

1,00

enter image description here

My Idea was to catch this in my main.py, but the problem is that the default error message from WTForms triggers first:

I tried to convert the float to string, check if , is in this string and use a simple replace(",",".") and then convert back to float.


An other side question, how do I change this default Not a valid float value message to a custom message?

Thanks!

like image 235
Roman Avatar asked Oct 28 '25 18:10

Roman


1 Answers

You can subclass FloatField and add the replace function to its process_formdata() function.

class MyFloatField(FloatField):
    def process_formdata(self, valuelist):
        if valuelist:
            try:
                self.data = float(valuelist[0].replace(',', '.'))
            except ValueError:
                self.data = None
                raise ValueError(self.gettext('Not a valid float value'))

Here you can also change the Error message.

like image 172
MrLeeh Avatar answered Oct 31 '25 08:10

MrLeeh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!