Issue
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!
Solution
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.
Answered By - MrLeeh
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.