Wagtail: How to verify if a user can access a page in the template

本秂侑毒 提交于 2020-01-25 00:13:05

问题


I am creating a personal website using Django with Wagtail, in which users belonging to different groups can access certain pages. For example, the family group can see my holiday photos, while the co-workers group can see some internal documents.

Setting up permissions access permission is very straightforward through the admin. However, I would like to show a lock next to the link to forbidden pages. This will make it very clear to the user which links can be followed and which ones can't.

Is there any way to verify whether the current user has access to a given page?


回答1:


After fiddling around with Wagtail's code, I've found that the permissions are handled through a model called PageViewRestriction (the code is very succinct and clear), which in turns inherits BaseViewRestriction that defines a method accept_request. Since the page to which is referring is store in the model, the only missing piece is the user requesting access.

With this, I've managed to put together a very simple template tag, which checks whether the current user can see the given page. The filter looks like this:

@register.simple_tag(takes_context=True)
def can_view(context, page):
    pvrs = PageViewRestriction.objects.filter(page=page)
    request = context['request']
    if pvrs:
        for pvr in pvrs:
            if pvr.accept_request(request):
                return True
        return False
    return True

Which in turn I use in my template like this:

{% can_view menuitem as permission %}
  {% if not permission %}
    <i class="fas fa-lock"></i>
  {% endif %}

Note that in principle a page can have multiple different permissions specified. For example, members of different groups can view it. I assumed that if the current user belongs to one of those groups, or if the page does not specify view permissions, then the user can access that page.



来源:https://stackoverflow.com/questions/59022143/wagtail-how-to-verify-if-a-user-can-access-a-page-in-the-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!