首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在基于django类的视图上使用permission_required装饰器

如何在基于django类的视图上使用permission_required装饰器
EN

Stack Overflow用户
提问于 2011-05-20 16:01:12
回答 13查看 103.8K关注 0票数 170

我在理解新的CBV是如何工作的时候遇到了一些麻烦。我的问题是,我需要在所有视图中登录,并且在其中一些视图中需要特定的权限。在基于函数的视图中,我使用视图中的@permission_required()和login_required属性执行此操作,但我不知道如何在新视图中执行此操作。django文档中有没有解释这一点的部分?我什么也没找到。我的代码出了什么问题?

我尝试使用@method_decorator,但它回复"TypeError at /spaces/prueba/ _wrapped_view()接受至少1个参数(给定0)

以下是代码(GPL):

代码语言:javascript
复制
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
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6069070

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档