使用 FieldList 在 WTForm 的选择字段中动态分配选项
Dynamically assign choices in an selectfield of WTForm using a FieldList
类似于这个问题:
在我的烧瓶应用程序中,我有一个带有多个选择字段的 WTForm。我想动态分配selectfields的数量和selectfields的选择。
class FormEntry(FlaskForm):
selectfield = SelectField('Name', coerce=int, choices=[('1', 'default_choice1'), ('2', 'default_choice2')])
class MyForm(FlaskForm):
form_entries = FieldList(FormField(FormEntry), min_entries=1)
创建了一个 FormEntry 实例并分配了选项:
my_entry = FormEntry()
my_entry.selectfield.choices =[('3', 'mychoice3'), ('4', 'mychoice4')]
但是,当我使用此条目创建表单实例时,选项不是我选择的选项而是默认选项:
form_entries = [my_entry, my_entry]
form = MyForm(form_entries=form_entries)
for entry in form.form_entries:
print(entry.selectfield.choices)
打印输出:
[('1', 'default_choice1'), ('2', 'default_choice2')]
[('1', 'default_choice1'), ('2', 'default_choice2')]
出了什么问题,我该如何正确分配选项?
https://wtforms.readthedocs.io/en/stable/fields.html#wtforms.fields.SelectField
来自文档(强调我的)
Note that the choices keyword is only evaluated once, so if you want to make a dynamic drop-down list, you’ll want to assign the choices list to the field after instantiation. Any inputted choices which are not in the given choices list will cause validation on the field to fail.
即没有selectfield = SelectField('Name', coerce=int, choices=[('1', 'default_choice1'), ('2', 'default_choice2')]
请改用 selectfield = SelectField('Name', coerce=int)
。
类似于这个问题:
在我的烧瓶应用程序中,我有一个带有多个选择字段的 WTForm。我想动态分配selectfields的数量和selectfields的选择。
class FormEntry(FlaskForm):
selectfield = SelectField('Name', coerce=int, choices=[('1', 'default_choice1'), ('2', 'default_choice2')])
class MyForm(FlaskForm):
form_entries = FieldList(FormField(FormEntry), min_entries=1)
创建了一个 FormEntry 实例并分配了选项:
my_entry = FormEntry()
my_entry.selectfield.choices =[('3', 'mychoice3'), ('4', 'mychoice4')]
但是,当我使用此条目创建表单实例时,选项不是我选择的选项而是默认选项:
form_entries = [my_entry, my_entry]
form = MyForm(form_entries=form_entries)
for entry in form.form_entries:
print(entry.selectfield.choices)
打印输出:
[('1', 'default_choice1'), ('2', 'default_choice2')]
[('1', 'default_choice1'), ('2', 'default_choice2')]
出了什么问题,我该如何正确分配选项?
https://wtforms.readthedocs.io/en/stable/fields.html#wtforms.fields.SelectField
来自文档(强调我的)
Note that the choices keyword is only evaluated once, so if you want to make a dynamic drop-down list, you’ll want to assign the choices list to the field after instantiation. Any inputted choices which are not in the given choices list will cause validation on the field to fail.
即没有selectfield = SelectField('Name', coerce=int, choices=[('1', 'default_choice1'), ('2', 'default_choice2')]
请改用 selectfield = SelectField('Name', coerce=int)
。