我正在尝试在烧瓶中制作动态表格。我遵循documentation on dynamic forms,一切顺利。我不喜欢这个布局。该文档显示了从父类创建表单类,然后在视图中为其添加属性。我认为可以创建一个窗体类,并向其传递一个值列表,以便在实例化时动态为其设置属性。
执行此操作时,出现错误 “ wtforms.fields.core.UnboundField对象”没有属性...然后设置缺少的任何属性,然后弹出一个新属性。因此感觉像是hack子,感觉不正确。
我的第一次尝试:
class PathsForm(FlaskForm):
def __init__(self, paths, *args, **kwargs):
super().__init__(*args, **kwargs)
self.paths = paths
i=0
row_list = []
for path in self.paths:
param_name = 'param_{}'.format(str(i))
custom_param_name = 'custom_param_{}'.format(str(i))
path_name = 'path_{}'.format(str(i))
parameter = SelectField('Parameter', choices = [('',''),
('choice_1', 'Choice 1'),
('choice_2', 'Choice 2'),
])
parameter.id = param_name
custom_parameter = StringField('Custom Parameter')
custom_parameter.id = custom_param_name
path_field = SelectField('Path')
path_field.choices = [('','')]+[(path,path) for path in self.paths]
setattr(self, param_name, parameter)
setattr(self, custom_param_name, custom_parameter)
setattr(self, path_name, path_field)
row_list.append((param_name, custom_param_name, path_name))
i += 1
self.row_list = row_list
cbt_id = HiddenField('CBT ID', validators = [DataRequired()])
submit = SubmitField('Submit')
我能够使表格在第二次尝试时呈现,但是它将所有名称和ID设置为均等,这给验证造成了严重破坏。我可以通过设置类属性并将其动态传递给表单来实现。
第二次尝试:
class PathsForm(FlaskForm):
parameter = SelectField('Parameter', choices = [('',''),
('choice_1', 'Choice 1'),
('choice_2', 'Choice 2'),
])
custom_parameter = StringField('Custom Parameter')
path_field = SelectField('Path')
def __init__(self, paths, *args, **kwargs):
super().__init__(*args, **kwargs)
self.paths = paths
i=0
row_list = []
for path in self.paths:
param_name = 'param_{}'.format(str(i))
custom_param_name = 'custom_param_{}'.format(str(i))
path_name = 'path_{}'.format(str(i))
self.path_field.choices = [('','')]+[(path,path) for path in self.paths]
setattr(self, param_name, self.parameter)
setattr(self, custom_param_name, self.custom_parameter)
setattr(self, path_name, self.path_field)
row_list.append((param_name, custom_param_name, path_name))
i += 1
self.row_list = row_list
cbt_id = HiddenField('CBT ID', validators = [DataRequired()])
submit = SubmitField('Submit')
问题:
wtforms.fields.core.UnboundField对象是什么意思,为什么在第一个示例中而不是第二个示例中得到它?
是否可以做我想做的事情?还是应该回到文档中如何在视图功能中看到所有这些内容?
感谢您的任何反馈。