Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get child pages of specified type in Wagtail (or Django)

Tags:

django

wagtail

I have the following code to get the child pages of the current one:

{% for subpage in self.get_children %}
    ...
{% endfor %}

This is used, for example, to show a gallery of images (each children page have an image).

However, this works fine when only I have one type of children, but, when I try to add another child page (for example to show testimonials), the code above doesn't filter for children type ..so it shows all childs.

I want to know if there is another way to make this work or if my approach is wrong (the use of children pages).

Any help would be appreciated :-)

like image 259
Giovanni Benussi Avatar asked May 19 '16 22:05

Giovanni Benussi


1 Answers

It's often easier to do these kinds of queries in Python code, rather than inside the template. Wagtail page objects provide a get_context method where you can set up additional variables to be passed into the template:

class GalleryIndexPage(Page):
    # ... field definitions here ...

    def get_context(self, request):
        context = super(BlogIndexPage, self).get_context(request)
        context['image_pages'] = self.get_children().type(ImagePage)
        return context

In this code, type is one of the methods Wagtail provides for filtering a queryset - see Page QuerySet reference for the full list.

With this method defined, you can then access the variable image_pages within your template:

{% for subpage in image_pages %}
    ...
{% endfor %}
like image 169
gasman Avatar answered Oct 09 '22 03:10

gasman