【问题标题】:How can I use the blog index within the homepage?如何使用主页内的博客索引?
【发布时间】:2020-05-12 09:12:01
【问题描述】:

我是 wagtail 的新手,对 django 还是很陌生。我想知道如何实现此处记录的博客:

https://docs.wagtail.io/en/stable/getting_started/tutorial.html

但直接在主页内。意思是,我希望博客索引成为网站的根目录(就像大多数博客网站一样)。

提前致谢!

【问题讨论】:

    标签: django wagtail


    【解决方案1】:

    您可以将您的博客“帖子”(例如 BlogPage)添加为主页下的直接子级。

    这意味着您的博客页面 URL 将直接位于根 URL 之下。 例如mydomain.com/my-cool-post/.

    注意:首页下的其他页面将共享此路由区域(例如/contact-us/)。

    基本上只是按照教程中的步骤进行操作,但忽略有关BlogIndex 的部分。保持 BlogPage 模型不变,在管理 UI 中添加子项时,将它们添加到主页下。

    如果您想列出HomePage 模板上的所有帖子,您可以修改模板上下文以返回类似于documentationblog_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 %}
    

    【讨论】:

    • 谢谢 - 在这种情况下,我会按照说明运行 python manage.py startapp blog 吗?或者只是在 my-app/models.py 中添加 BlogPage 模型?
    • 这取决于您,如果您的网站很小,您可能不需要为blog 区域添加新应用。如果您想将它们放在单独的应用程序中,您可能需要通过apps.get_model 动态拉入BlogPage 模型。但是,保持简单可能是一个好的开始,一个应用程序暂时可以。
    【解决方案2】:

    简单,在 urls.py 中使用重定向,如下代码:

    from django.views.generic import RedirectView
    urlpatterns = [
        path(r'^$', RedirectView.as_view(url='/blog/', permanent=False)),
        # pass other paths
    ]
    

    【讨论】:

    • 就是这样 - 我不想重定向。我根本不希望 /blog 存在。如果您访问 gizmodo.com,它会提供博客文章列表……它不需要在任何地方重定向到 /blog。我希望我能用 wagtail 做到这一点。
    • 所以,您可以找到博客视图,并直接将主页 url 路径到它。我想你可以弄清楚。
    猜你喜欢
    • 2021-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多