【问题标题】:How to restrict access to certain groups in django class based view如何在基于 django 类的视图中限制对某些组的访问
【发布时间】:2021-05-03 14:31:59
【问题描述】:

我的views.py 混合了defClassViews

@login_required(login_url='login')
@allowed_users(allowed_roles=['Admin', 'Staff', 'Lite Scan'])
def litescan(request):
    filteredOutput = Stock.objects.all()
    val = {}...

@method_decorator(login_required(login_url='login'), name='dispatch')
class HomeView(ListView):
    model = Post
    template_name = 'community.html'
    ordering = ['-id']

如果有帮助,这里是我的decorators.py

from django.shortcuts import redirect
from django.http import HttpResponseRedirect


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

    return wrapper_func

def allowed_users(allowed_roles=[]):
    def decorator(view_func):
        def wrapper_func(request, *args, **kwargs):

            group = None
            if request.user.groups.exists():
                group = request.user.groups.all()[0].name

            if group in allowed_roles:
                return view_func(request, *args, **kwargs)
            else:
                url = ('/forbidden')
                return HttpResponseRedirect(url)
        return wrapper_func
    return decorator

我发现@login_required@allowed_users 在与ClassView 一起使用时会出错。所以我使用了@method_decorator,它在重定向到页面之前将我带到了登录页面。但是,我无法通过我的ClassView 来限制对某些组的访问,例如AdminStaffLite Scan

我们将不胜感激。谢谢!

【问题讨论】:

    标签: python django django-views


    【解决方案1】:

    您可以将 AccessMixin 用于您的班级视图。

    我找到的例子:

    from django.contrib.auth.mixins import AccessMixin
    from django.http import HttpResponseRedirect 
    
    class FinanceOverview(AccessMixin, TemplateMixin):
    
        def dispatch(self, request, *args, **kwargs):
            if not request.user.is_authenticated:
                # This will redirect to the login view
                return self.handle_no_permission()
            if not self.request.user.groups.filter(name="FinanceGrp").exists():
                # Redirect the user to somewhere else - add your URL here
                return HttpResponseRedirect(...)
    
            # Checks pass, let http method handlers process the request
            return super().dispatch(request, *args, **kwargs)
    

    在此处找到更多信息:Use LoginRequiredMixin and UserPassesTestMixin at the same time

    【讨论】:

    • 没关系,但是当我输入if not self.request.user.groups.filter(name="Admin", "Lite Scan").exists(): 时,它会出错
    • 我不能分多个组
    • 你能用and吗? `如果不是 self.request.user.groups.filter(name="Admin") 而不是 self.request.user.groups.filter(name="OtherGroup")
    • And 没有用,但你的建议让我想到在休息后放第二行,它工作正常。谢谢大佬!
    【解决方案2】:

    依靠Django Permissions 可能是一种更简单的方法来访问此类视图。您可以为这些组分配权限,并根据用户的组是否具有适当的权限来授予对视图的访问权限,而不是检查特定的组列表。

    views.py

    from django.contrib.auth.decorators import permission_required
    from django.contrib.auth.mixins import PermissionsRequiredMixin
    
    
    @permission_required('foo.view_bar')
    def my_view(request):
        ...
    
    
    class MyView(PermissionRequiredMixin, DetailView):
        permission_required = ('foo.view_bar', )
        ...
    

    【讨论】:

      猜你喜欢
      • 2021-05-16
      • 2022-09-30
      • 2019-12-28
      • 2014-10-10
      • 2012-09-29
      • 2019-06-12
      • 2016-12-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多