每个 Wagtail 页面上的 Django 表单,例如base.html 页脚中的联系表
Django-forms on every Wagtail page, e.g. Contact form in the footer of base.html
我想在基于 wagtail cms 框架的多页网站的页脚中使用 django-forms 实现一个联系表单。如何在每个页面上呈现 base.html 模板中的表单?谢谢!
在 settings.py
所在的根文件夹中创建一个 middleware.py
。然后将其添加到该文件中
class SimpleMiddleware:
def __init__(self, get_response):
self.get_response = get_response
# One-time configuration and initialization.
def __call__(self, request):
# Code to be executed for each request before
# the view (and later middleware) are called.
request.contact_form = ContactForm()
response = self.get_response(request)
# Code to be executed for each request/response after
# the view is called.
return response
我建议将其实现为 inclusion template tag:
@register.inclusion_tag('contact_form.html')
def contact_form():
return {'form': ContactForm()}
contact_form.html
模板将包含表单的 HTML。然后,您可以将其作为 base.html 的一部分包含在标签中:{% contact_form %}
虽然您希望联系表单出现在每个页面上,但我仍然会制作一个专用的 ContactFormPage 并将表单放在每个页脚中。 POST 请求应指向此专用的 ContactFormPage。
<form action='{% pageurl contact_page' %}' ...>
优点是:
- 当联系表包含错误时,您在专用页面上
专注于手头的任务。
- 发生错误时无需滚动回页脚。
- 通过RoutablePageMixin轻松添加成功页面
- 可共享的联系表url
表格 html 可以通过以下方式包含:
- 包含模板标签(Gasmans 的回答)
- 中间件(shouravs 答案)
我想在基于 wagtail cms 框架的多页网站的页脚中使用 django-forms 实现一个联系表单。如何在每个页面上呈现 base.html 模板中的表单?谢谢!
在 settings.py
所在的根文件夹中创建一个 middleware.py
。然后将其添加到该文件中
class SimpleMiddleware:
def __init__(self, get_response):
self.get_response = get_response
# One-time configuration and initialization.
def __call__(self, request):
# Code to be executed for each request before
# the view (and later middleware) are called.
request.contact_form = ContactForm()
response = self.get_response(request)
# Code to be executed for each request/response after
# the view is called.
return response
我建议将其实现为 inclusion template tag:
@register.inclusion_tag('contact_form.html')
def contact_form():
return {'form': ContactForm()}
contact_form.html
模板将包含表单的 HTML。然后,您可以将其作为 base.html 的一部分包含在标签中:{% contact_form %}
虽然您希望联系表单出现在每个页面上,但我仍然会制作一个专用的 ContactFormPage 并将表单放在每个页脚中。 POST 请求应指向此专用的 ContactFormPage。
<form action='{% pageurl contact_page' %}' ...>
优点是:
- 当联系表包含错误时,您在专用页面上 专注于手头的任务。
- 发生错误时无需滚动回页脚。
- 通过RoutablePageMixin轻松添加成功页面
- 可共享的联系表url
表格 html 可以通过以下方式包含:
- 包含模板标签(Gasmans 的回答)
- 中间件(shouravs 答案)