Validating Select Fields in Flask WTF Forms


Question

I am using Flask-WTF forms and I have the following code:

in forms.py

class DealForm( Form ):
    country  = SelectField( 'Country' )

in main.py

if not form.validate_on_submit():
    form = DealForm()
    form.country.choices = [('us','USA'),('gb','Great Britain'),('ru','Russia')]
    return render_template( 'index.html', user = current_user, form = form )
else:
    return render_template( 'index.html', form = form )

It gets an error when I return from the POST because the country.choices is None What am I doing wrong?

1
4
10/17/2014 7:30:44 PM

You need to set the choices before calling validate_on_submit().

Since they are static do it when creating the Form class:

class DealForm(Form):
    country = SelectField('Country', choices=[
        ('us','USA'),('gb','Great Britain'),('ru','Russia')])

If you wanted to set them after creating the form instance, e.g. because the available choices are not hardcoded or different depending on other factors, you'd do it like this after creating the instance of the class:

form.country.choices = [('us','USA'),('gb','Great Britain'),('ru','Russia')]

I.e. just like you already did but earlier.

11
10/17/2014 7:37:14 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon