无需构建任何东西(至少在服务器端) - WTForms 已经支持您需要的东西 - 它称它们为“字段附件”。您正在寻找的行为是在wtforms.fields.FormField
和wtforms.fields.FieldList
class ContactForm(Form):
name = TextField("Name", validators=[Required()])
contact_type = SelectField("Contact Type",
validators=[Required()],
choices=[
("email", "Email"),
("phone", "Phone Number"),
("im", "Instant Message")
])
# `If` is a custom validator - see below
email_address = TextField("Email",
validators=[If("contact_type",
"email",
[Required(), Email()])
])
phone_number = TextField("Phone #",
validators=[If("contact_type",
"phone", [Required()])
])
im_handle = TextField("IM Handle",
validators=[If("contact_type",
"im", [Required()])
])
class SignUpForm(Form):
# Other fields go here
contacts = FieldList(FormField(ContactForm))
根据用户的选择,您还需要一个自定义验证器来验证相应的字段:
# CAUTION: Untested code ahead
class If(object):
def __init__(self,
parent,
run_validation=None,
extra_validators=None,
msg=None):
self.parent = parent
self.msg = msg if msg is not None else u"Invalid"
if callable(run_validation):
self.run_validation = run_validation
else:
_run_validation = lambda self, parent, form: parent.data == run_validation
self.run_validation = _run_validation
self.extra_validators = extra_validators if extra_validators is not None \
else []
def __call__(self, field, form):
parent = getattr(form, self.parent)
if self.run_validation(parent, form):
return field.validate(form, extra_validators=self.extra_validators)
当您form.validate()
在服务器端调用时,将根据要求自动检查字段,并适当地填充错误,以便您可以将它们呈现回客户端。
在客户端创建新字段很简单,只要您使用它使用的相同命名约定命名,WTForms 就会在后端提取它们- 即field.short_name + '-' + index
.