【问题标题】:Dynamically assign choices in an selectfield of WTForm using a FieldList [duplicate]使用 FieldList 在 WTForm 的选择字段中动态分配选项
【发布时间】:2019-10-05 12:58:12
【问题描述】:

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

在我的烧瓶应用程序中,我有一个带有多个选择字段的 WTForm。我想动态分配选择字段的数量和选择字段的选择。

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

出了什么问题,如何正确分配选项?

【问题讨论】:

  • 建议的重复问题不正确;它不是重复的。我也遇到了这个问题,发现这篇文章很有用。

标签: python flask wtforms


【解决方案1】:

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

来自文档(重点是我的)

请注意,choices 关键字只评估一次,因此如果您想制作一个动态下拉列表,您需要将选择列表分配给字段after 实例化。任何不在给定选项列表中的输入选项都将导致字段验证失败。

即没有selectfield = SelectField('Name', coerce=int, choices=[('1', 'default_choice1'), ('2', 'default_choice2')] 请改用selectfield = SelectField('Name', coerce=int)

【讨论】:

  • 谢谢。但如果我不为选项提供默认值,我会得到“TypeError: 'NoneType' object is not iterable”。
  • 您是否仍在通过.choices 设置选择,或者尽管大卫主义在他自己的答案的链接中建议(尽管在validate_on_submit 之前)?
  • 到目前为止,仍然通过 '.choices' 设置选项。如果我然后删除构造函数中的默认选项,上面的打印输出变为:无,无。
  • 最后对我有用的方法与您的上一条评论非常相似:form = MyForm({}) 然后form.form_entries[0].selectfield.choices = whatever。所以我接受这个答案。感谢您的帮助。
  • 但是,我仍然不明白为什么我的问题中的代码不起作用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-03-30
  • 1970-01-01
  • 2021-06-14
  • 2023-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多