如何在django基于类的视图上使用permission_required decorators [英] How to use permission_required decorators on django class-based views

本文介绍了如何在django基于类的视图上使用permission_required decorators的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很了解新的CBV如何工作有点麻烦。我的问题是这样,我需要登录所有的视图,并在其中一些具体的权限。在基于功能的视图中,我使用@permission_required()和view_required属性在视图中执行,但我不知道如何在新视图上执行此操作。 django文档中有一些部分解释这一点吗?我没有找到任何东西我的代码有什么问题?



我尝试使用@method_decorator,但它回覆了 TypeError at / spaces / prueba / _wrapped_view()至少需要1参数(0给定)



以下是代码(GPL):

从django.contrib.auth.decorators导入login_required $ permission $ _ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $

显示空格的索引页获取各种额外的上下文以获取该空间的
信息

get_object方法在用户'

context_object_name ='get_place'
template_name =空的字段,如果当前的
空格是允许的,如果不允许,他被重定向到 'space / space_index.html'

@method_decorator(login_required)
def get_object(self):
space_name = self.kwargs ['space_na我']

为我在self.request.user.profile.spaces.all():
如果i.url == space_name:
返回get_object_or_404(空格,网址= space_name)

self.template_name ='not_allowed.html'
return get_object_or_404(Space,url = space_name)

#获取额外的上下文数据
def get_context_data(self,** kwargs):
context = super(ViewSpaceIndex,self).get_context_data(** kwargs)
place = get_object_or_404(Space,url = self.kwargs ['space_name'])
上下文['entities'] = Entity.objects.filter(space = place.id)
上下文['documents'] = Document.objects.filter(space = place.id)
上下文['proposal'] = Proposal.objects.filter(space = place.id).order_by(' - pub_date')
上下文['publication'] = Post.objects.filter(post_space = place.id) .order_by(' - post_pubdate')
返回上下文


解决方案

CBV文档


  1. 在您的网址中添加装饰器.py 路线,例如 login_required(ViewSpaceIndex.as_view(..))


  2. 使用 method_decorator 装饰您的CBV的调度方法,例如



    $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ b $ :
    template_name ='secret.html'

    Django 1之前。你不能在类上使用 method_decorator ,所以你必须覆盖 dispatch 方法:

      class ProtectedView(TemplateView):

    @method_decorator(login_required)
    def dispatch(self,* args ,** kwargs):
    return super(ViewSpaceIndex,self).dispatch(* args,** kwargs)


  3. 使用访问混合,如 django.contrib.auth.mixins.LoginRequiredMixin 可用于Django 1.9+,并在其他答案中概述了。


文档中解释了您收到 TypeError 的原因:


注意:
method_decorator将* args和** kwargs作为参数传递给类上的装饰方法。如果您的方法不接受一组兼容的参数,它将引发TypeError异常。



I'm having a bit of trouble understanding how the new CBVs work. My question is this, I need to require login in all the views, and in some of them, specific permissions. In function-based views I do that with @permission_required() and the login_required attribute in the view, but I don't know how to do this on the new views. Is there some section in the django docs explaining this? I didn't found anything. What is wrong in my code?

I tried to use the @method_decorator but it replies "TypeError at /spaces/prueba/ _wrapped_view() takes at least 1 argument (0 given)"

Here is the code (GPL):

from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required, permission_required

class ViewSpaceIndex(DetailView):

    """
    Show the index page of a space. Get various extra contexts to get the
    information for that space.

    The get_object method searches in the user 'spaces' field if the current
    space is allowed, if not, he is redirected to a 'nor allowed' page. 
    """
    context_object_name = 'get_place'
    template_name = 'spaces/space_index.html'

    @method_decorator(login_required)
    def get_object(self):
        space_name = self.kwargs['space_name']

        for i in self.request.user.profile.spaces.all():
            if i.url == space_name:
                return get_object_or_404(Space, url = space_name)

        self.template_name = 'not_allowed.html'
        return get_object_or_404(Space, url = space_name)

    # Get extra context data
    def get_context_data(self, **kwargs):
        context = super(ViewSpaceIndex, self).get_context_data(**kwargs)
        place = get_object_or_404(Space, url=self.kwargs['space_name'])
        context['entities'] = Entity.objects.filter(space=place.id)
        context['documents'] = Document.objects.filter(space=place.id)
        context['proposals'] = Proposal.objects.filter(space=place.id).order_by('-pub_date')
        context['publication'] = Post.objects.filter(post_space=place.id).order_by('-post_pubdate')
        return context

解决方案

There are a few strategies listed in the CBV docs:

  1. Add the decorator in your urls.py route, e.g., login_required(ViewSpaceIndex.as_view(..))

  2. Decorate your CBV's dispatch method with a method_decorator e.g.,

    from django.utils.decorators import method_decorator
    
    @method_decorator(login_required, name='dispatch')
    class ProtectedView(TemplateView):
        template_name = 'secret.html'
    

    Before Django 1.9 you can't use method_decorator on the class, so you have to override the dispatch method:

    class ProtectedView(TemplateView):
    
        @method_decorator(login_required)
        def dispatch(self, *args, **kwargs):
            return super(ViewSpaceIndex, self).dispatch(*args, **kwargs)
    

  3. Use the access mixins like django.contrib.auth.mixins.LoginRequiredMixin available in Django 1.9+ and outlined well in the other answers here.

The reason you're getting a TypeError is explained in the docs:

Note: method_decorator passes *args and **kwargs as parameters to the decorated method on the class. If your method does not accept a compatible set of parameters it will raise a TypeError exception.

这篇关于如何在django基于类的视图上使用permission_required decorators的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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