Django组权限如何在模板中打印 [英] Django Group permission how to print it in template

查看:76
本文介绍了Django组权限如何在模板中打印的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果客户登录并且他有权查看管理员提供给他的数据,则他将在登录后看到该数据,但是如果管理员未授予他权限,则该消息将显示您无权查看此页面

if the customer sign in and he has permission to see the data that the admin has given to him, he will see the data after he sign in, but if the admin doesn't give him permission, this message will appear You are not authorized to view this page

就我而言,无论给予管理员什么权限,此消息始终出现您无权查看此页面

in my case no matter what the permission given the admin this message always appears You are not authorized to view this page

from .decorators import unathenticated_user, allowed_users,staff_only
from django.contrib.auth.models import Group

@login_required(login_url='loginpage')
@staff_only

def adminpage(request):
    return render(request, 'Homepage/adminsite.html')
def loginpage(request):
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(username=username, password=password)
        if user:
            username = request.POST['username']
            request.session['username'] = username
            return redirect('adminpage')
        else:

            return render(request, 'Homepage/adminlogin.html')

    return render(request, 'Homepage/adminlogin.html')

这是我的decorators.py

this is my decorators.py

from django.http import HttpResponse
from django.shortcuts import redirect




def unauthenticated_user(view_func):
    def wrapper_func(request, *args, **kwargs):
        if request.user.is_staff:
            return redirect('adminpage')
        else:
            return view_func(request, *args, **kwargs)
    return wrapper_func



def allowed_users(allowed_roles=None):
    if allowed_roles is None:
        allowed_roles = []
    def decorator(view_func):
        def wrapper_func(request, *args, **kwargs):
            group = None
            if request.user.groups.exists():
                return redirect('adminpage')
            if group in allowed_roles:
                return view_func(request, *args, **kwargs)
            else:
                return HttpResponse('You are not authorized to view this page')
        return wrapper_func
    return decorator

def staff_only(view_func):
    def wrapper_function(request, *args, **kwargs):
        group = None
        if request.user.groups.exists():
            group = request.user.groups.all()[0].name

        if group == 'registrar':
            return redirect('adminpage')

        if group == 'admin':
            return view_func(request, *args, **kwargs)

    return wrapper_function

这是我的管理网站(权限)

this is my admin site (permission)

这是我的登录名

我登录后(更新错误)

预先感谢

这是我的html

注意,我不知道此html是否有效.由于我的逻辑错误,对此我感到抱歉,我只想打印admin授予客户的权限.

NOTE I dont know if this html is working. because of my logic error, I am sorry for that, I just want to print the permissions that admin given to the customer.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
{% if request.user|group:"registrar" %}
    <p>User belongs to my group</p>
{% else %}
    <p>User does not belong to my group</p>
{% endif %}

</body>
</html>

这是我的urls.py

this is my urls.py

urlpatterns = [
       path('adminpage/', Homepage.views.adminpage, name='adminpage'),
       path('loginpage/', Homepage.views.loginpage, name='loginpage'),
  ]

这是我的html中的错误

this is the error in my html

如果您有任何问题,我很乐意提供答案以回答此问题

if you have any question, I am happy to provide an answer inorder to answer this question

推荐答案

您在问如何打印,但是显然您还有其他问题.另一个答案已解决您的 staff_only 装饰器上的问题.由于您并未涵盖所有情况,因此您的装饰器将返回None.另一位用户已对其进行了更正,但为了将所有内容都放在一个位置,我也将提供详细信息.

You are asking how to print but as obvious you have some other problems. The other answer has solved the problem on your staff_only decorator. Since you did not cover every case your decorator where returning None. It has been corrected by the other user but to make all in one place i will give detail too.

def staff_only(view_func):
    def wrapper_function(request, *args, **kwargs):
        group = None
        if request.user.groups.exists():
            groups = list(request.user.groups.all().values_list('name', flat=True))

        if 'admin' in groups or 'registrar' in groups:
            """I assume that registrar is also staff"""
            return view_func(request, *args, **kwargs)

        return redirect("loginpage")

    return wrapper_function

在装饰器中,您仅将用户放在第一组并比较其名称.但是,用户可能有多个组.因此,您需要检查整个列表.我上面的解决方案将所有组都放在列表中,并检查是否符合条件,并继续查看或重定向.

In your decorator you were only taking users first group and compare it's name. However users may have multiple groups. Thus you need to check the whole list. My solution above gets all groups in a list and check if it fits the conditions and do continue to the view or redirect.

在您的模板中,您使用的是不存在的模板过滤器 group .

In your template you are using not existing template filter group.

您可以将其更改为以下内容:

You may change it as following:

<body>
{% for group in request.user.groups.all %}
    {% if group.name == 'registrar' %}
        <p>User belongs to my group</p>
    {% endif %}
{% endfor %}
</body>

如果要打印所有组,可以执行以下操作.

If you want to print all groups you may do the following.

<body>
<ul>
{% for group in request.user.groups.all %}
    <li>{{group.name}}</li>
{% endfor %}
</ul>
</body>

但是,检查用户在模板中是否有组的最佳方法是为此目的创建模板过滤器.您可以查看文档.

However the best way of checking if user has a group in template is creating a template filter for that purpose. You can check documentation.

@register.filter(name='has_group')
def has_group(user, group_name):
    return user.groups.filter(name=group_name).exists()

在您的模板中:

<body>
{% if request.user|has_group:"registrar" %}
    <p>User belongs to my group</p>
{% else %}
    <p>User does not belong to my group</p>
{% endif %}
</body>

这篇关于Django组权限如何在模板中打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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