我已经看过文档和其他一些Q/As在这里,但我似乎无法让代码工作。我有一个forms.py文件的基本形式:将SelectMultipleField的动态数量添加到wtf-flask表格中
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)
UPDATE: 要调用的形式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应该是支持‘的GetList’方法的multidict型包装”
我超级接近这....我怎么实际上实现的意见页面?我完全可以做{{for field in form}},但实体的实际名称是什么?以前,我会通过'form.category_4'调用,但是这里有什么是jinja的名字? –
您使用flask-WTForms? – lesingerouge
我输入错误。我的意思是HTML页面。例如,对于定义的表单,我会写{{form.category_1}}。我如何为名称不同的动态字段做到这一点。 –