I want to create a floatfield in wtform to edit value in database, which can be left empty if we dont want to change the value of that attribute. But when i keep the field empty and submit form it gives the validation error msg, "Not a valid float value."
This is the code i used
def Inrange(form, field):
if form.movie_rating.data:
if 0 > int(form.movie_rating.data) < 10:
raise ValidationError('Rating should be from 0 to 10')
class EditForm(FlaskForm):
movie_rating = FloatField('Your Rating out of 10', validators=[Inrange])
review = StringField('Review')
# movie_id = HiddenField('id')
submit = SubmitField('Done')
I can leave the Stringfield empty without any problem but not the Floatfield.
Is there any way to fix this while still using the Floatfield? If not what are the other opions?
CodePudding user response:
You can use the validators provided by wtforms to validate the input.
Optional
allows empty fields and stops validation in this case.
The return value of the field is thenNone
.NumberRange
ensures that the input is within the defined range.
from wtforms.validators import (
NumberRange,
Optional
)
class EditForm(FlaskForm):
movie_rating = FloatField(
'Your rating out of 10',
validators=[
Optional(),
NumberRange(0, 10, 'Rating should be from 0 to 10')
]
)