【发布时间】:2020-05-12 09:12:01
【问题描述】:
我是 wagtail 的新手,对 django 还是很陌生。我想知道如何实现此处记录的博客:
https://docs.wagtail.io/en/stable/getting_started/tutorial.html
但直接在主页内。意思是,我希望博客索引成为网站的根目录(就像大多数博客网站一样)。
提前致谢!
【问题讨论】:
我是 wagtail 的新手,对 django 还是很陌生。我想知道如何实现此处记录的博客:
https://docs.wagtail.io/en/stable/getting_started/tutorial.html
但直接在主页内。意思是,我希望博客索引成为网站的根目录(就像大多数博客网站一样)。
提前致谢!
【问题讨论】:
您可以将您的博客“帖子”(例如 BlogPage)添加为主页下的直接子级。
这意味着您的博客页面 URL 将直接位于根 URL 之下。
例如mydomain.com/my-cool-post/.
注意:首页下的其他页面将共享此路由区域(例如/contact-us/)。
基本上只是按照教程中的步骤进行操作,但忽略有关BlogIndex 的部分。保持 BlogPage 模型不变,在管理 UI 中添加子项时,将它们添加到主页下。
如果您想列出HomePage 模板上的所有帖子,您可以修改模板上下文以返回类似于documentation 的blog_pages。
您可以通过type using exact_type 过滤页面查询集。或者,如下图,你可以用BlogPage.childOf(...)换一种方式查询。
关于 the queryset api 的 Django 文档。
my-app/models.py
class HomePage(Page):
body = RichTextField(blank=True)
content_panels = Page.content_panels + [
FieldPanel('body', classname="full"),
]
def get_context(self, request):
context = super().get_context(request)
# Add extra variables and return the updated context
# note: be sure to get the `live` pages so you do not show draft pages
context['blog_pages'] = BlogPage.objects.child_of(self).live()
return context
my-app/templates/home_page.html
{{ page.title }}
{% for blog_page in blog_pages %}
{{ blog_page.title }}
{% endfor %}
【讨论】:
blog 区域添加新应用。如果您想将它们放在单独的应用程序中,您可能需要通过apps.get_model 动态拉入BlogPage 模型。但是,保持简单可能是一个好的开始,一个应用程序暂时可以。
简单,在 urls.py 中使用重定向,如下代码:
from django.views.generic import RedirectView
urlpatterns = [
path(r'^$', RedirectView.as_view(url='/blog/', permanent=False)),
# pass other paths
]
【讨论】: