g:如何验证用户是否可以访问模板中的页面 [英] Wagtail: How to verify if a user can access a page in the template

查看:98
本文介绍了g:如何验证用户是否可以访问模板中的页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用带有Wagtail的Django 创建一个个人网站,属于不同组的用户可以访问某些页面.例如,家庭小组可以看到我的假期照片,而同事小组可以看到一些内部文档.

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.

通过管理员非常简单地设置访问权限.但是,我想在 forbidden 页面的链接旁边显示一个锁.这将使用户非常清楚哪些链接可以被跟踪,哪些链接不能被跟踪.

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?

推荐答案

摆弄Wagtail的代码后,我发现权限是通过名为PageViewRestriction的模型(

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.

这篇关于g:如何验证用户是否可以访问模板中的页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆