【问题标题】:Wagtail Feedback form in homepage主页上的鹡鸰反馈表
【发布时间】:2018-02-06 06:17:55
【问题描述】:

告诉我如何在主页上而不是在其单独的模板中获取 Wagtail 表单,因为我不需要借出和另一个页面。我找不到如何在 Home 模型的 get_context 中指定它

【问题讨论】:

  • 您想在您的主页中获得 Wagtail Form Builder 表单吗?这意味着您已经设置了一个 FormPage 模型,并且您已经有一个专门的联系页面或类似的东西?还是您只是想接受开发人员编写的主页上的某种形式?
  • 将主页模型的代码和模板的相关部分放在您希望放置表单的位置可能会有所帮助。
  • 这个答案有帮助吗? stackoverflow.com/a/47214504/8070948
  • 是的,没错。正如你所说,我使用了所有这些,并且表单有一个单独的页面。那些。在该页面上,表单字段(自然)出现,而根(主页)不起作用,我认为它是通过 get_context 完成的,但我不知道如何在那里获得它。

标签: django forms wagtail


【解决方案1】:

这与关于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 模型。
  • 然后我们限制@9​​87654327@内的链接,在示例中我们的FormPage模型位于base应用程序中,因此['base.FormPage]
  • 然后我们重写 get_context 方法,这是我们需要这样做的唯一真正原因,因为它为我们提供了当前的 requestFormPage.getForm 需要使用当前的请求。
  • 最后,我们非常接近文档中的form rendering example 更新我们的模板。不同之处在于我们的表单 POST URL 实际上是 form_page 而不是当前页面(主页)。
  • 重要提示:表单实际上是POST到表单页面,而不是您的主页,这意味着我们不需要处理对home_page的任何类型的POST请求。这是一个简单的解决方案,但这意味着着陆页将在表单页面的 URL 上呈现。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多