Learn Wagtail CMS Course

Getting Child Page Properties From a Subclassed Page

When you subclass a page in Wagtail and then create a query for all the parent pages, you'll also receive all the child pages with it. Sometimes that's good, sometimes that's bad. In the scenarios where you need additional child page fields you can't simply loop through your QuerySet and get them all. Instead, you'll need to use .specific in your template, or .specific(defer=False) in your view.

Below is an example of a QuerySet that's looped in our template, and some model assumptions.

# models.py 
from django.db import models 


class YourParentPage(Page):
    """Your Parent Page. Subclasses inherit this."""

    custom_title = models.CharField(max_length=100)

class YourChildPage(YourParentPage):
    """Your Child Page. Inherits From YourParentPage."""

    subtitle = models.CharField(max_length=100)
# In your terminal 
all_posts = YourParentPage.objects.all()
all_posts
<PageQuerySet [<YourParentPage: Parent Page>, <YourChildPage:Child Article>]>
{# In your template #}
{% for post in all_posts %}
    {{ post.title }} {# This is a wagtailcore.Page property; comes with all Page's #}
    {% if post.specific.subtitle %}
        <p>{{ post.specific.subtitle }}</p>
    {% endif %}
{% endfor %}

In the above template we're checking for .specific which basically means: Check if there's a child page and if that child page has a property/field called subtitle.

The Git Commit

If you'd like to see the entire git commit, you can check it out here: https://github.com/CodingForEverybody/learn-wagtail/commit/08fbcd67748cec18d9fd8a59fd3c775f6be07aae