Setting default value after initialization in SelectField flask-WTForms
Once an instance of the form is created, the data is bound. Changing the default after that doesn't do anything. The reason changing choices
works is because it affects validation, which doesn't run until validate
is called.
Pass default data to the form constructor, and it will be used if no form data was passed. The default will be rendered the first time, then posted the second time if the user doesn't change the value.
form = AddressForm(request.form, country='US')
(If you're using Flask-WTF's Form
you can leave out the request.form
part.)
I know that you probably fixed the problem. But I think it doesn't work anymore. And because this is the first thing that shows up when googleing the problem, I want to give people with this problem a working solution(at least for me).
To confirm the change of the default choice, we have to add address_form.process()
.
Thats it!
The full solution would be:
class AddressForm(Form):
country = SelectField('Country') # works
address_form = AddressForm()
address_form.country.choices=[('GB', 'Great Britan'), ('US', 'United States')]
address_form.country.default='US'
address_form.process() # works