Restricting Parent and Child Pages
When you have a lot of different page types in your Wagtail CMS website, you'll eventually "Add a Child Page" and see that every page you have is available for creation.
In most cases, you'll want to restrict these to some degree.
A good example is a Blog Index Page (or Blog Listing Page). Should you be able to add a Home Page under the Blog Index Page? Probably not, because it won't have the same fields as a regular Blog Detail Page, so creating a proper Index page with images, summaries, and other blog related info isn't an option, and your template will look awkward.
To restrict this, we employ 2 methods:
- Add a rule to the parent page about what child pages it can have, and
- Add a rule to the child page about parent pages it can have
Like all things Wagtail, this is incredibly simple to implement. Each option is one line. That's right. One line of code (per option above) to immediately start guiding your client and/or content entry team about which pages belong where. Let's dive into this.
from wagtail.core.models import Page class HomePage(Page): """Home page model.""" subpage_types = [ 'blog.BlogListingPage', # appname.ModelName 'contact.ContactPage', # appname.ModelName 'flex.FlexPage', # appname.ModelName ] parent_page_type = [ 'wagtailcore.Page' # appname.ModelName ]
Ok if you're saying "That's more than one line of code!", you're right, it's been broken down on multiple lines for better readability. But they are just Python lists, so you can put them all on one line if you really wanted to.
In the above code we're telling the Home Page to only live under the main Wagtail Core Page (this is the Root page). And we're also saying that the child pages that can live under the Home Page are: Blog Listing Pages, Contact Pages and Flex Pages.
The Git Commit
Was this helpful to you?
Sharing is caring. Help the community by sharing this article.