我们有以下表单,我们正在尝试为每个组创建GroupRoleForms
列表。
class FullNameMixIn():
full_name = TextField(
'Full name', [
validators.required(message=u"Full name is required")
])
class GroupRoleForm(Form):
group =BooleanField('Group', default=False)
role = SelectField(
'Role',choices=[
("none", "----------"),
('approver', 'Approver'),
('editor', 'Editor')
])
class AdminEditUserForm(Form, FullNameMixIn):
group_roles = FieldList(FormField(GroupRoleForm))
我们如何创建包含预先填充的AdminEditUserForm
列表的GroupRoleForms
个实例?
目前我们正试图这样做:
form = forms.AdminEditUserForm()
for group in company.groups:
group_role_form = forms.GroupRoleForm()
group_role_form.group.label = group.name
group_role_form.group.name = group.id
form.group_roles.append_entry(group_role_form)
return dict(edit_user_form = form )
答案 0 :(得分:6)
在data
的{{1}}或formdata
个关键字参数中,您只需要一个与Form
匹配的字典,该字典与包含可迭代的key
子字段匹配。该可迭代需要的项目依次具有与FieldList
的字段列表匹配的属性。
如果你按照下面的例子我得到预先填充好的嵌套表格。
FieldList
from collections import namedtuple
from wtforms import validators
from wtforms import Form
from wtforms import SelectField
from wtforms import BooleanField
from wtforms import TextField
from wtforms import FieldList
from wtforms import FormField
from webob.multidict import MultiDict
# OP's Code
class FullNameMixIn():
full_name = TextField(
'Full name', [
validators.required(message=u"Full name is required")
])
class GroupRoleForm(Form):
group =BooleanField('Group', default=False)
role = SelectField(
'Role',choices=[
("none", "----------"),
('approver', 'Approver'),
('editor', 'Editor')
])
class AdminEditUserForm(Form, FullNameMixIn):
group_roles = FieldList(FormField(GroupRoleForm))
# create some groups
Group = namedtuple('Group', ['group', 'role'])
g1 = Group('group-1', 'none')
g2 = Group('group-2', 'none')
# drop them in a dictionary
data_in={'group_roles': [g1, g2]}
# Build form
test_form = AdminEditUserForm(data=MultiDict(data_in))
# test print
print test_form.group_roles()
答案 1 :(得分:1)
我对这些包不熟悉,但我会采取刺:
class AdminEditUserForm(Form, FullNameMixIn):
def __init__(self, groups):
super(AdminEditUserForm, self).__init__()
self.group_roles = FieldList(FormField(GroupRoleForm))
for group in groups:
self.group.label = group.name
self.group.name = group.id
self.group_roles.append_entry(self.group)
# If this doesn't create a copy of the GroupRoleForm
# superclass in group_roles, then you need a method to do it
self.__clear_group()
def __clear_group(self):
# copy GroupRoleForm object, if needed
# delete GroupRoleForm object
...
然后你可以这样称呼它:
form = forms.AdminEditUserForm(company.groups)