告诉我如何让Wagtail表单不在其单独的模板中,而是放在主页上,因为我不需要借阅和其他页面。我找不到如何在Home模型的get_context中指定它
答案 0 :(得分:2)
这与关于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.objects.get()
抓住第一个,但这是不好的做法,可能不可靠。这就是为什么我们将一个ForeignKey添加到wagtailcore.Page
- 注意我们这里没有链接到我们的FormPage模型。PageChooserPanel
内部的链接,在示例中我们的FormPage
模型位于base
应用中,因此['base.FormPage]
。get_context
方法,这是我们需要执行此操作的唯一真正原因,因为它让我们当前request
和FormPage.getForm
需要使用当前请求。