Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
318 views
in Technique[技术] by (71.8m points)

python - Wagtail: Display a list of child pages inside a parent page

In Wagtail CMS, I'm trying to create an index page that will display a list of all its child pages along with a featured image associated with each child page.

I have created these two page models in 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'),
    ]

In the template index_page.html, I added the following code:

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

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

This displays all of the child page titles, but not the images. Is it possible to retrieve the image fields for the child pages?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

From the release notes of wagtail version 1.1:

Usually, an operation that retrieves a queryset of pages (such as homepage.get_children()) will return them as basic Page instances, which only include the core page data such as title. The specific() method (e.g. homepage.get_children().specific()) now allows them to be retrieved as their most specific type, using the minimum number of queries.

Therefore you don't need your custom function in the upcoming release 1.1 anymore and you can change your template to:

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

At least since version 0.8 the following should work, too, using specific:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...