DEV Community

Adam Mateusz Brożyński
Adam Mateusz Brożyński

Posted on

Wagtail: check for user root page in admin panel (for menus & PageChooser etc.)

Wagtail navigation through pages is not very intuitive. If you have users with permissions per page, it's better to set PageChooser root to their root pages and add a menu link to easily edit their root pages.

1. Create a function for checking user root:

app/helpers.py:

from wagtail.permission_policies.pages import PagePermissionPolicy
from django.urls import reverse

def get_root_page(user):
    root_page = PagePermissionPolicy().explorable_root_instance(user)
    # we can also get edit_url link and other things…
    root_page.edit_url = reverse('wagtailadmin_pages:edit', args=[root_page.id])
    return root_page
Enter fullscreen mode Exit fullscreen mode

2. Register a hook to set PageChooser to user root:

app/wagtail_hooks.py:

from wagtail import hooks
from wagtail.admin.menu import MenuItem
from app.helpers import get_root_page

@hooks.register('construct_page_chooser_queryset')
def show_my_pages_only(pages, request):
    print(vars(get_root_page(request.user)))
    pages = pages.descendant_of(get_root_page(request.user),inclusive=True)
    return pages
Enter fullscreen mode Exit fullscreen mode

3. Register a hook to add menu item that allows to easily edit user root page (if his root is not main Wagtail Root):

app/wagtail_hooks.py:

@hooks.register('construct_main_menu')
def change_menu_items(request, menu_items):

    # let's get root page
    root_page = get_root_page(request.user)

    # we can also exclude some menus
    exclude = [
         "help",
         "reports",
    ]

    menu_items[:] = [item for item in menu_items if (item.name not in exclude) ]

    # now we add edit user root page menu item (if it's not main ROOT)
    if (root_page.id and root_page.id!=1):
        menu_items += [MenuItem('Main: '+root_page.title, root_page.edit_url, classnames='icon icon-home', order=-99999)]
Enter fullscreen mode Exit fullscreen mode

Top comments (0)