pythondjangowagtailwagtail-admin

Is it possible to override a wagtail.hooks.register function with a custom function?


Is it possible to override a wagtail @hooks.register function with a custom function or to de-register a function all together?

One example of what I would like to achieve is editing the register_styleguide_menu_item function in wagtail/contrib/styleguide/wagtail_hooks.py so that the style guide is only shown to superusers.

For example; I would like to override the current function:

@hooks.register("register_settings_menu_item")
def register_styleguide_menu_item():
    return MenuItem(
        _("Styleguide"), reverse("wagtailstyleguide"), icon_name="image", order=1000
    )

with this:

@hooks.register("register_settings_menu_item")
def register_styleguide_menu_item():
    return AdminOnlyMenuItem(
        _("Styleguide"), reverse("wagtailstyleguide"), icon_name="image", order=1000
    )

(note the change from MenuItem to AdminOnlyMenuItem on the third line)

The docs for wagtail hooks are available at https://docs.wagtail.org/en/stable/reference/hooks.html but it doesn't cover this scenario.

Is there a mechanism to achieve this?


Solution

  • To modify the menu items based on the request you will need to use a different hook.

    Either construct_main_menu for the main menu or construct_settings_menu for the settings menu.

    from wagtail.core import hooks
    
    @hooks.register('construct_settings_menu')
    def hide_styleguide_menu_item(request, menu_items):
      if not request.user.is_superuser:
        menu_items[:] = [item for item in menu_items if item.name != 'styleguide']
    

    Note: the item.name may not be exactly 'styleguide' it may be 'Styleguide'.