Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating Select Fields in Flask WTF Forms

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?

like image 818
CrabbyPete Avatar asked Dec 20 '22 20:12

CrabbyPete


1 Answers

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.

like image 182
ThiefMaster Avatar answered Dec 28 '22 09:12

ThiefMaster