这与关于putting a form on every page 的问题/答案非常相似。
不过,这里有一种方法可以实现此解决方案。
示例
在你的 my_app/models.py -
class HomePage(Page):
"""A Page model that represents the home page at the root of all pages."""
# must have way to know WHICH FormPage to use, this makes it user editable
form_page = models.ForeignKey(
'wagtailcore.Page',
blank=True,
null=True,
on_delete=models.SET_NULL,
related_name='embedded_form_page',
help_text='Select a Form that will be embedded on this page.')
# ... all other fields
def get_context(self, request, *args, **kwargs):
"""Add a renderable form to the page's context if form_page is set."""
# context = super(HomePage, self).get_context(request, *args, **kwargs) # python 2.7 syntax
context = super().get_context(request, *args, **kwargs)
if self.form_page:
form_page = self.form_page.specific # must get the specific page
# form will be a renderable form as per the dedicated form pages
form = form_page.get_form(page=form_page, user=request.user)
context['form'] = form
return context
content_panels = Page.content_panels + [
PageChooserPanel('form_page', ['base.FormPage']), # Important: ensure only a FormPage model can be selected
#... other fields
]
然后在你的模板 my_app/templates/my_app/home_page.html
<div>
{% if self.form_page %}
<form action="{% pageurl self.form_page %}" method="POST" role="form">
{% csrf_token %}
{{ form.as_p }} {# form is avaialable in the context #}
<input type="submit">
</form>
{% endif %}
</div>
说明
- 首先,我们提供了一种方法来了解我们要呈现哪个 FormPage,我们可以假设只使用
FormPage.objects.get() 抓取第一个,但这是不好的做法,并且可能不可靠。这就是我们向 wagtailcore.Page 添加 ForeignKey 的原因 - 请注意,我们没有在此处链接到 FormPage 模型。
- 然后我们限制@987654327@内的链接,在示例中我们的
FormPage模型位于base应用程序中,因此['base.FormPage]。
- 然后我们重写
get_context 方法,这是我们需要这样做的唯一真正原因,因为它为我们提供了当前的 request 和 FormPage.getForm 需要使用当前的请求。
- 最后,我们非常接近文档中的form rendering example 更新我们的模板。不同之处在于我们的表单 POST URL 实际上是 form_page 而不是当前页面(主页)。
- 重要提示:表单实际上是POST到表单页面,而不是您的主页,这意味着我们不需要处理对home_page的任何类型的POST请求。这是一个简单的解决方案,但这意味着着陆页将在表单页面的 URL 上呈现。