12

在 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 %}

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

4

2 回答 2

23

wagtail 版本 1.1 的发行说明

通常,检索页面查询集(例如homepage.get_children())的操作会将它们作为基本 Page 实例返回,其中仅包含核心页面数据,例如标题。该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 %}
于 2015-09-07T10:46:59.760 回答
5

我找到了这个解决方案:将函数 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 %}
于 2015-09-06T23:11:13.553 回答