WTForms:如何选择SelectMultipleField中的选项? [英] WTForms: How to select options in SelectMultipleField?
问题描述
可以使用 form.myfield.choices = [(1,Choice1),(2,Choice2)]
p>
设置选定选项的方法是什么?
创建字段时使用选项
和默认
关键字参数,如下所示:
my_choices = [('1','Choice1'),('2','Choice2'),('3','Choice3')]
SelectMultipleField(choices = my_choices,default = ['1','3'])
这会将选项1和3标记为选中状态。
编辑:默认值在表单处于安装状态时显然会被处理(复制到 data
成员中),所以之后更改默认值将不会产生任何效果,除非手动调用领域。您可以设置数据
- 成员,如下所示:
form。 myfield.data = ['1','3']
但我不确定是否这是一个很好的做法。
编辑:如果您想真正设置数据,而不是默认值,您应该使用表单来加载数据。
表单
对象需要 formdata
作为第一个参数,并使用它自动填充字段值。 (你应该使用一个包含getlist的字典包装 - 方法)
创建表单时也可以使用关键字参数来设置数据,如下所示:
form = MyForm(myfield = ['1','3'])
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'])
这篇关于WTForms:如何选择SelectMultipleField中的选项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!