FLASK-WTF Make a Floatfield which can be left blank

Issue

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?

Solution

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 then None.

  • 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')
        ]
    )

Answered By – Detlef

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published