I am using WTForms with Flask, (not Flask-wtf). I am using the SelectMultipleFields where I set choices dynamically;
class MyForm(Form):
country = SelectMultipleField("Country", option_widget=widgets.CheckboxInput(),
widget=widgets.ListWidget(prefix_label=False))
As I said, the choices are dynamically, I query the database to get new countries, then I set the choices, something like;
form = MyForm(request.form, obj=user) # obj = user's sqlalchemy object
form.country.choices = [(c.title(), c.title()) for c in get_distinct_countries()]
Where get_distinct_countries queries the database and returns a list with countries[('country a', 'country a'), ('country b', 'country b', (...)]
All of this works fine, but now I want to set the default, which is also dynamically, so I tried this;
form = PersonalForm(request.form, obj=user)
form.country.choices = [(c.title(), c.title()) for c in get_distinct_countries()] # to fix
form.country.default = [(i.title(), i.title()) for i in get_user_country(userid)]
This is my get_countries and get_user_country function;
def get_user_country(id): # todo
with session_scope() as session:
countries = session.query(UserCountry).filter_by(user_id=id)
return [c.country for c in countries.all()]
def get_distinct_countries(): # todo
"""Returns a list of all countries (without duplication)"""
with session_scope() as session:
countries = session.query(Country).distinct(Country.country).group_by(Country.country)
return [i.country.capitalize() for i in countries.all()]
The output of get_user_country is something like [('country a, 'country a'), (...)]
Didn't work, I don't get any traceback, but when checking the form field, nothing is set as default. How can I make this work?
Note, I pass the obj=user, because this is a form where the user will re-edit his settings, so I expect the data to be there, apparently I see everything correctly, except the data for the countries.
Thanks.
I realize this is very late, but I found this page while googling the same issue. As other users have pointed out, to set the highlighted fields dynamically, you must set form.field.data (not form.field.default). The desired selections must be wrapped in a list (even if it's a single choice). Use only the "value" member of the (value, label) tuples you provide for choices. In your case, the code will be:
form.country.data = [i.title() for i in get_user_country(userid)]
This won't work:
form.country.data = [(i.title(), i.title()) for i in get_user_country(userid)]
If you wanted a single default, this wouldn't work either:
form.country.data = "some value"
But this would:
form.country.data = ["some value"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With