将 SelectMultipleField 的动态数量添加到 wtf-flask 表单

Add dynamic number of SelectMultipleField's to wtf-flask form

我查看了此处的文档和其他一些 Q/As,但我似乎无法使代码正常工作。我在 forms.py 文件中有一个基本表格:

class SimpleForm(Form):
    list_of_files = ['Option 1','Option 2','Option 3','Option 4','Option 5','Option 6']
    files = [(x, x) for x in list_of_files]
    acheckbox = MultiCheckboxField('Label',choices=files)
    third_list = ['Special Analysis']
    third_files = [(x, x) for x in third_list] 
    bcheckbox = MultiCheckboxField('Label', choices=third_files)
    category_1 = SelectField(u'', choices=())
    category_2 = SelectField(u'', choices=())
    category_3 = SelectField(u'', choices=())

(我稍后填充类别)。我也在我的 views.py 文件中调用此表单。

form = SimpleForm()

我想动态添加多个 SelectMultipleField(取决于用户上传的 csv 文件中的列数)。我想传递一个带有列名称 n=1-5 的列表变量(类别),并使用另一个列表 (unique_values) 生成那么多字段,这些字段是该字段的值。我正在查看文档并试图想出这个:

class F(Form):
    pass

    F.category = SelectMultipleField('category')
    for name in extra:
        setattr(F, name, SelectMultipleFields(name.title()))
    form = F(request.POST, ...)

我知道这样不对。如何修改以将 SelectMultipleField 附加到我的原始 "SimpleForm?" 我最终想生成以下 n 个数字:

unique_values = [('1', 'Choice1'), ('2', 'Choice2'), ('3', 'Choice3')]
category_4 = SelectMultipleField(u"",choices=unique_values)

更新: 要在 views.py 上调用表单,我使用以下命令:

select_dict = {'Geography': ['US', 'Asia', 'Europe'], 'Product Type': ['X', 'Y', 'Z']}
form= F(request.form,select_dict)

我的子类(在 forms.py 上)是:

class F(SimpleForm):
pass
#select_dict could be a dictionary that looks like this: {category_+str(col_number): set of choices}
def __init__(self, select_dict, *args, **kwargs):
    super(SimpleForm, self).__init__(*args, **kwargs)
    print(select_dict)
    for name,choices in select_dict.items():
        test = [(x, x) for x in choices]
        setattr(F, name, SelectMultipleField(name.title(),choices=test))

我收到以下错误:"formdata should be a multidict-type wrapper that supports the 'getlist' method"

基本上您要做的是附加到 SimpleForm 可变数量的 SelectMultipleField 元素,每个元素都有不同的选择集。

首先,要将 SelectMultipleField 元素添加到原始 SimpleForm 中,您应该在定义 F 时将其子类化(而不是原始的 Form) .

其次,您可以使用您已经编写的大部分代码,如下所示:

class F(SimpleForm):
    pass

#select_dict could be a dictionary that looks like this: {category_+str(col_number): set of choices}
for name,choices in select_dict.items():
    setattr(F, name, SelectMultipleFields(name.title(),choices=choices))

form = F(request.POST, ...)

要在模板中呈现动态表单,您需要自定义 Jinja 过滤器(查看 this answer) and maybe a simpler way to render a field (like described on this page)。