代码之家  ›  专栏  ›  技术社区  ›  Leo

无法将博客文章链接到Wagtail中的内容页

  •  0
  • Leo  · 技术社区  · 9 年前

    我在创建一个博客帖子的链接时遇到了一个问题。在我的模型中,我有两个页面类,BlogPage和IndexPage。My BlogPage类用于创建博客文章,IndexPage类用来显示博客文章列表。

    请参见以下型号:

    from django.db import models
    
    from modelcluster.fields import ParentalKey
    
    from wagtail.wagtailcore.models import Page, Orderable
    from wagtail.wagtailcore.fields import RichTextField
    from wagtail.wagtailadmin.edit_handlers import FieldPanel, MultiFieldPanel, InlinePanel
    from wagtail.wagtailimages.edit_handlers import ImageChooserPanel
    from wagtail.wagtailsearch import index
    
    
    class IndexPage(Page):
        intro = RichTextField(blank=True)
    
        def child_pages(self):
            return BlogPage.objects.live()
    
    
        content_panels = Page.content_panels + [
            FieldPanel('intro', classname='full'),
        ]
    
        subpage_types = ['blog.BlogPage']
    
    
    class BlogPage(Page):
        date = models.DateField("Post date")
        intro = models.CharField(max_length=250)
        body = RichTextField(blank=True)
    
    
    
        search_fields = Page.search_fields + (
        index.SearchField('intro'),
        index.SearchField('body'),
        )
    
        content_panels = Page.content_panels + [
        FieldPanel('date'),
        FieldPanel('intro'),
        FieldPanel('body', classname="full")
        ]
    

    我的挑战是,我不知道如何将索引页上的博客文章链接到自己的页面。我需要创建一个单独的页面模型和html模板来实现这一点吗?或者解决这个问题的最佳方法是什么?

    1 回复  |  直到 9 年前
        1
  •  2
  •   doru    9 年前

    您可以创建一个include模板(它不需要模型)-让我们命名它 truncated_blog_post.html -然后可以在 index_page.html 样板这将是推荐的方法,因为使用包含模板可以在任何需要显示(通常被截断)帖子列表的地方使用它:例如,当您希望帖子位于某个标签下时。

    truncated_blog_post.html

    {% load wagtailcore_tags %}
    
    <article>
      <a href="{% pageurl blog %}"><h2>{{ blog.title }}</h2></a>
      <p>{{ blog.date }}</p>
      <p>{{ blog.body|truncatewords:40 }}</p>
    </article>
    

    使用 pageurl 标签来自 wagtailcore_tags 你会得到那篇博客文章的相对URL。显然,如果您不想为截短的帖子创建包含模板,可以将 article 代码来自 blog_post.html 直接在for循环中 index_page.html 样板

    而你的 index_page.html 模板:

    ....
    {% for blog in blogs %}
      {% include "path/to/includes/truncated_blog_post.html" %}
    {% empty %}
      No posts found
    {% endfor %}
    ....
    

    为此,您必须修改 IndexPage 型号:

    class IndexPage(Page):
        intro = RichTextField(blank=True)
        @property
        def blogs(self):
            blogs = BlogPage.objects.live()
            return blogs
        def get_context(self, request):
            # Get blogs
            blogs = self.blogs
    
            # Update template context
            context = super(IndexPage, self).get_context(request)
            context['blogs'] = blogs
            return context
    
        content_panels = Page.content_panels + [
        FieldPanel('intro', classname='full'),
        ]
        subpage_types = ['blog.BlogPage']