Reputation: 534
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?
Upvotes: 4
Views: 6426
Reputation: 318488
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.
Upvotes: 11