Python Flask WTForms FloatField allow 1,0 and 1.0 allow comma and dot
Question:
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
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!
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.
I would like to suggest use of DecimalField instead of FloatField
It will let you avoid taking care of dots and commas.
i.e.:
preis = DecimalField('Preis p.P.', places=2, validators=[Optional()])
I also attach a small hint from https://wtforms.readthedocs.io/en/3.0.x/fields/#basic-fields
class wtforms.fields.DecimalField(default field arguments, places=2,
rounding=None, use_locale=False, number_format=None)[source]
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
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!
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.
I would like to suggest use of DecimalField instead of FloatField
It will let you avoid taking care of dots and commas.
i.e.:
preis = DecimalField('Preis p.P.', places=2, validators=[Optional()])
I also attach a small hint from https://wtforms.readthedocs.io/en/3.0.x/fields/#basic-fields
class wtforms.fields.DecimalField(default field arguments, places=2,
rounding=None, use_locale=False, number_format=None)[source]