Wagtail按用户权限隐藏/显示菜单项

时间:2018-05-20 11:12:48

标签: wagtail wagtail-snippet

如何在wagtail CMS中隐藏显示菜单: 这是我在blog/wagtail_hooks.py

内的register_admin_menu_item钩子上的代码
    from wagtail.core import hooks
    from wagtail.admin.menu import MenuItem
    @hooks.register('register_admin_menu_item')
    def register_custom_admin_menu_item():
        return MenuItem(_('Site Admin'), reverse('admin_menu'), classnames='icon icon-folder-inverse',
         order=20000)

1 个答案:

答案 0 :(得分:1)

要在菜单上强加访问权限,我们可以创建自定义MenuItem类并覆盖is_shown方法,如下所示:

        class CustomAdminMenuItem(MenuItem):
        def is_shown(self, request):
            return request.user.is_staff

现在使用此CustomAdminMenuItem代替MenuItem,如:

    from wagtail.core import hooks
    from wagtail.admin.menu import MenuItem
    @hooks.register('register_admin_menu_item')
    def register_custom_admin_menu_item():
        return CustomAdminMenuItem(_('Site Admin'), reverse('admin_menu'), classnames='icon icon-folder-inverse',
         order=20000)

您也可以使用is_shown中的has_perm来实现自定义权限检查,例如:

    class CustomMenuItem(MenuItem):
        def is_shown(self, request):
            return (
                request.user.has_perm('wagtailsearchpromotions.add_searchpromotion') or
                request.user.has_perm('wagtailsearchpromotions.change_searchpromotion') or
                request.user.has_perm('wagtailsearchpromotions.delete_searchpromotion')
            )

有关详细信息,请访问源代码here和文档here