Choices can be set using form.myfield.choices=[("1","Choice1"), ("2","Choice2")]
What is the way to set the selected option?
You can use the choices
and default
keyword arguments when creating the field, like this:
my_choices = [('1', 'Choice1'), ('2', 'Choice2'), ('3', 'Choice3')]
SelectMultipleField(choices = my_choices, default = ['1', '3'])
This will mark choices 1 and 3 as selected.
Edit: Default values are apparently processed (copied into the data
member) when the form is instatiated, so changing the default afterwards won't have any effect, unless you manually call process() on the field. You could set the data
-member, like so:
form.myfield.data = ['1', '3']
But I'm not sure if either of them is a good practice.
Edit: In case you want to actually set the data and not the default, you should probably use the form to load the data.
Form
objects take formdata
as the first argument and use that to automatically populate field values. (You are supposed to use a dictionary wrapper with a getlist -method for that)
You can also use keyword arguments to set the data when creating the form, like this:
form = MyForm(myfield = ['1', '3'])