使用FieldLis在WTForm的selectfield中动态分配选项

2024-10-05 15:18:27 发布

您现在位置:Python中文网/ 问答频道 /正文

类似于这个问题: Dynamic choices WTForms Flask SelectField

我的应用程序中有几个字段在我的应用程序中。我想动态分配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的实例并分配选项:

^{pr2}$

但是,当我使用此项创建窗体实例时,这些选项不是我选择的选项,而是默认选项:

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')]

出了什么问题?我如何才能正确分配选项?在


Tags: form应用程序default选项classchoicesentriesentry
1条回答
网友
1楼 · 发布于 2024-10-05 15:18:27

https://wtforms.readthedocs.io/en/stable/fields.html#wtforms.fields.SelectField

来自文档(emphasis mine)

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)。在

相关问题 更多 >