以编程方式将表单字段添加到 Wagtail 表单
Add form fields programmatically to Wagtail Form
我有一个子类 AbstractEmailForm
..
的模型
我可以创建一个新实例:
new_page = LanderPage(body='body text here', title='Test sub page',
slug='testsub', to_address='j@site.com',from_address='j@site.com', subject='new inquiry')
这行得通,但它会生成一个没有字段的表单。我不确定如何使用此结构创建表单字段,例如姓名和电子邮件地址的表单字段。
有人能指出我正确的方向吗?
作为参考,这是正在创建的页面:
class LanderPageFormField(AbstractFormField):
page = ParentalKey('LanderPage', related_name='form_fields')
class LanderPage(AbstractEmailForm):
body = RichTextField(blank=True)
thank_you_text = RichTextField(blank=True)
content_panels = AbstractEmailForm.content_panels + [
FieldPanel('body', classname="full"),
InlinePanel('form_fields', label="Form fields"),
FieldPanel('thank_you_text', classname="full"),
MultiFieldPanel([
FieldRowPanel([
FieldPanel('from_address', classname="col6"),
FieldPanel('to_address', classname="col6"),
]),
FieldPanel('subject'),
], "Email"),
]
可通过关系 new_page.form_fields
访问表单字段 - 检查 the definition of AbstractFormField in the Wagtail source 以获取要提供的字段。例如:
new_page.form_fields = [
LanderPageFormField(label="Name", field_type="singleline", required=True),
LanderPageFormField(label="Email", field_type="email", required=True),
]
(由于关系被定义为 ParentalKey,可以在保存 new_page
之前将它们附加到对象,这对于标准的 Django ForeignKey 是不可能的。)
我有一个子类 AbstractEmailForm
..
我可以创建一个新实例:
new_page = LanderPage(body='body text here', title='Test sub page',
slug='testsub', to_address='j@site.com',from_address='j@site.com', subject='new inquiry')
这行得通,但它会生成一个没有字段的表单。我不确定如何使用此结构创建表单字段,例如姓名和电子邮件地址的表单字段。
有人能指出我正确的方向吗?
作为参考,这是正在创建的页面:
class LanderPageFormField(AbstractFormField):
page = ParentalKey('LanderPage', related_name='form_fields')
class LanderPage(AbstractEmailForm):
body = RichTextField(blank=True)
thank_you_text = RichTextField(blank=True)
content_panels = AbstractEmailForm.content_panels + [
FieldPanel('body', classname="full"),
InlinePanel('form_fields', label="Form fields"),
FieldPanel('thank_you_text', classname="full"),
MultiFieldPanel([
FieldRowPanel([
FieldPanel('from_address', classname="col6"),
FieldPanel('to_address', classname="col6"),
]),
FieldPanel('subject'),
], "Email"),
]
可通过关系 new_page.form_fields
访问表单字段 - 检查 the definition of AbstractFormField in the Wagtail source 以获取要提供的字段。例如:
new_page.form_fields = [
LanderPageFormField(label="Name", field_type="singleline", required=True),
LanderPageFormField(label="Email", field_type="email", required=True),
]
(由于关系被定义为 ParentalKey,可以在保存 new_page
之前将它们附加到对象,这对于标准的 Django ForeignKey 是不可能的。)