10

I use parent_page_types and subpage_types happily all around my Page-models.

But I'm stuck at allowing my class HomePage(Page) only as a direct child at root level.

Any hints?

tombreit
  • 1,199
  • 8
  • 27

3 Answers3

28

Try this:

parent_page_types = ['wagtailcore.Page']

also, for completeness, to allow only one instance of a Homepage, add this classmethod to your HomePage:

@classmethod
def can_create_at(cls, parent):
    # You can only create one of these!
    return super(HomePage, cls).can_create_at(parent) \
        and not cls.objects.exists()
Serafeim
  • 14,962
  • 14
  • 91
  • 133
  • Wow! That was fast - and that's exactly what I was looking for, thank you. – tombreit May 11 '16 at 16:26
  • Works for Wagtail 2 and in Django 2. – Kalob Taulien Jun 04 '18 at 18:34
  • I logged in specially to give you a thumbs up (Y) – Ibrahim Awad Mar 04 '19 at 15:10
  • 2
    The second part of @serafim answer - allow only one instance of a page model - now seems to be part of wagtails page methods/properties via ``max_count`` (and that should work even on multisite setups): http://docs.wagtail.io/en/v2.4/reference/pages/model_reference.html#wagtail.core.models.Page.max_count – tombreit Apr 17 '19 at 19:50
  • 4
    And now in v2.5 the more useful property `max_count_per_parent` exists. http://docs.wagtail.io/en/v2.5/reference/pages/model_reference.html#wagtail.core.models.Page.max_count_per_parent – Cloud_Ratha Jul 01 '19 at 12:23
2

First of all, thumbs up for @Serafeim answer, but I will post my answer for people searching for issue similar to mine.

I wanted to achieve the same thing but for a specifi parent in multi-site mode. Meaning I wanted to have multiple site "HomePage" but each "HomePage" can only include one "SearchIndexPage". So the above answer would be modified to

    @classmethod
    def can_create_at(cls, parent):
        # You can only create one of these!
        return super(SearchIndexPage, cls).can_create_at(parent) \
               and parent.get_children().type(SearchIndexPage).count() == 0
Ibrahim Awad
  • 498
  • 1
  • 6
  • 13
0

Updated Answer: If you are landing here on 2023 like me there is an easier way to do this now. Just add max_count prop to your model like so:

class HomePage(Page):
    #...

    max_count = 1
Marios Frixou
  • 227
  • 2
  • 9