django-templateswagtail

Wagtail. How to get a list of child pages through one category higher in the tree


I'm not good at English. I have been looking for a solution to my problem for a long time. There is such a category tree:

class ProductPage(Page):
    parent_page_types = ['CatalogSubPage']
    pass
    
class ProductSubPage(Page):
    parent_page_types = ['ProductPage']
    pass

    
    
class ProductSubSubPage(Page):
    parent_page_types = ['ProductSubPage']
    pass

I can’t find how to display child pages of “ProductPage” or adjacent pages of “ProductSubPage” on the “ProductSubSubPage” page.


Solution

  • Use get_parent to retrieve the parent, then get_siblings to fetch its adjacent pages.

    class ProductSubSubPage(Page):
        parent_page_types = ['ProductSubPage']
    
        def get_context(self, request, *args, **kwargs):
            context = super().get_context(request, *args, **kwargs)
            context['adjacent_pages'] = self.get_parent().get_siblings().live().specific()
            return context
    

    You can then access adjacent_pages in the template, e.g. {% for page in adjacent_pages %}.