I would like to pre-select the value for SelectField
when displaying it to user. default
argument works when it is passed at the time of instantiation but does not work once the field is initialized.
class AddressForm(Form):
country = SelectField('Country',choices=[('GB', 'Great Britan'), ('US', 'United States')], default='GB') # works
When I try to use default
value to preselect option before presenting the form to user for editing, it doesn't work.
address_form = AddressForm()
address_form.country.default='US' # doesnot work
Need a solution to set default value to pre-set values before presenting to the user.
Scenario 2: Also does not work
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' # doesnot work
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.)
来源:https://stackoverflow.com/questions/36157362/setting-default-value-after-initialization-in-selectfield-flask-wtforms