Wagtail:显示父页面内的子页面列表

时间:2015-09-06 23:02:26

标签: python django wagtail

在Wagtail CMS中,我尝试创建一个索引页面,该页面将显示其所有子页面的列表以及与每个子页面关联的特色图像。

我在models.py中创建了这两个页面模型:

class IndexPage(Page):
    intro = RichTextField(blank=True)

    content_panels = Page.content_panels + [
        FieldPanel('intro', classname='full'),
    ]

    subpage_types = ['myapp.ItemPage']


class ItemPage(Page):
    representative_image = models.ForeignKey(
        'wagtailimages.Image',
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name='+'
    )

    body = RichTextField(blank=True)

    promote_panels = Page.promote_panels + [
        ImageChooserPanel('representative_image'),
    ]

    content_panels = Page.content_panels + [
        FieldPanel('body', classname='full'),
    ]

在模板index_page.html中,我添加了以下代码:

<div class="intro">{{ self.intro|richtext }}</div>

{% for page in self.get_children %}
  {{ page.title }}
  {% image page.representative_image width-400 %}
{% endfor %}

这将显示所有子页面标题,但不显示图像。是否可以检索子页面的图像字段?

2 个答案:

答案 0 :(得分:17)

来自release notes of wagtail version 1.1

  

通常,检索页面查询集(例如homepage.get_children())的操作会将它们作为基本页面实例返回,这些实例仅包含核心页面数据,例如title。 specific()方法(例如homepage.get_children().specific())现在允许使用最少数量的查询将其作为最具体的类型进行检索。

因此,您不再需要在即将发布的1.1版中使用自定义功能,并且可以将模板更改为:

{% for page in self.get_children.specific %}
    {{ page.title }}
    {% image page.representative_image width-400 %}
{% endfor %}

至少从版本0.8开始,以下内容也可以使用specific

{% for page in self.get_children %}
    {{ page.title }}
    {% image page.specific.representative_image width-400 %}
{% endfor %}

答案 1 :(得分:3)

我找到了这个解决方案:将一个函数child_pages添加到IndexPage:

class IndexPage(Page):
    intro = RichTextField(blank=True)

    def child_pages(self):
        return ItemPage.objects.live().child_of(self)

    content_panels = Page.content_panels + [
        FieldPanel('intro', classname='full'),
    ]

    subpage_types = ['myapp.ItemPage']

这可以在模板中访问:

{% for page in self.child_pages %}
  {{ page.title }}
  {% image page.representative_image width-400 %}
{% endfor %}