nils nils - 1 year ago 80
Python Question

Wagtail: Get previous or next sibling

I'm creating a page with wagtail where I need to know the previous and next sibling of the current page:

In my portrait page model, I tried to define two methods to find the correct urls, but I'm missing a crucial part. To get the first sibling, I can just do the following:

class PortraitPage(Page):


def first_portrait(self):
return self.get_siblings().live().first().url

There is the
method, but there doesn't seem to be a
method to get the direct neighbours (in the order that they are arranged in the wagtail admin).

Is there any way to achieve this?

Answer Source

After going through the debugger for a while, I found out that wagtail already has two methods: get_prev_sibling() and get_next_sibling().

So the methods could look like this (accounting for the first page in the previous method and the last item in the next method):

def prev_portrait(self):
    if self.get_prev_sibling():
        return self.get_prev_sibling().url
        return self.get_siblings().last().url

def next_portrait(self):
    if self.get_next_sibling():
        return self.get_next_sibling().url
        return self.get_siblings().first().url