[Answered ]-Django: check if the object has a parent and a grandparent

1๐Ÿ‘

โœ…

If there is no parent, then self.object.parent is None, and this has no .parent.

You thus should only check if it has a grandparent, if it at least has a parent, so:

def get_success_url(self):
    parent = self.object.parent
    if parent:
        grandparent = parent.parent
        if grandparent:
            return reverse(
                'about:detail',
                kwargs={
                    'grandparent': grandparent.slug,
                    'parent': parent.slug,
                    'page': self.object.slug,
                },
            )
        else:
            return reverse(
                'about:detail',
                kwargs={'parent': parent.slug, 'page': self.object.slug},
            )
    else:
        return reverse('about:detail', kwargs={'page': self.object.slug})

For the last one, since there is no parent, we can only put the page on the context of the URL reversing, not its parent.

Leave a comment