我不太明白新的CBV是怎么工作的.我的问题是,我需要在所有视图中登录,并且在其中一些视图中需要特定的权限.在基于函数的视图中,我使用视图中的@PERMISSION_REQUIRED()和LOGIN_REQUIRED属性执行此操作,但我不知道如何在新视图上执行此操作.Django 的文件里有没有解释这一点的章节?我什么也没找到.我的代码中有什么错误?

我try 使用@method_decorator,但它返回"TypeError at /spaces/prueba/ _wrapped_view() takes at least 1 argument (0 given)"

以下是代码(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

推荐答案

the CBV docs强中列出了几种策略:

Decorate the view when you instantiate it in your urls.py (docs)

urlpatterns = [
    path('view/',login_required(ViewSpaceIndex.as_view(..)),
    ...
]

decorator 是按实例应用的,因此您可以根据需要在不同的urls.py个路由中添加或删除它.

Decorate your class so every instance of your view is wrapped (docs)

有两种方法可以做到这一点:

  1. method_decorator应用于你的CBV调度方法,例如:.,

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

如果您使用的是Django<;1.9(您不应该使用Django<;1.9,它已不再受支持),则不能在类上使用method_decorator,因此您必须手动覆盖dispatch方法:

    class ViewSpaceIndex(TemplateView):

        @method_decorator(login_required)
        def dispatch(self, *args, **kwargs):
            return super(ViewSpaceIndex, self).dispatch(*args, **kwargs)
  1. 使用类似于django.contrib.auth.mixins.LoginRequiredMixin的混合剂,在这里的其他答案中列出:

     from django.contrib.auth.mixins import LoginRequiredMixin
    
     class MyView(LoginRequiredMixin, View):
    
         login_url = '/login/'
         redirect_field_name = 'redirect_to'
    

确保将Mixin类放在继承列表的第一位(这样Python的Method Resolution Order algorithm Select 了正确的东西).

文件中解释了你得TypeError分的原因:

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

Django相关问答推荐

如何将Django项目连接到容器化的PostgreSQL数据库?

如何在 Django 中设置与 Session 相关的字段

Django 相当于子查询

如何在Django中制作一个不 Select 以前日期的日期 Select 器

如何计算 Django 模型中特定对象的数量?

使用django提交后如何保留html表单数据?

在 python 视图中检测移动浏览器

Django:如何在表单 clean() 方法的 django 验证错误中添加 超链接?

Django rest框架覆盖ViewSet中的page_size

Django 模板文件夹

Django 自定义管理器 - 如何仅返回登录用户创建的对象?

Django App 配置不当 - 应用程序模块有多个文件系统位置

virtualenv(python3.4), pip install mysqlclient 错误

Django:创建索引:非唯一,多列

如何在 Django Rest Framework SimpleRouter 上使斜杠可选

get_or_create() 线程安全吗

UnicodeEncodeError:ascii编解码器无法编码字符

如何在 Django/Python 中减go 两个日期?

Django Admin:如何在内联中显示模型上定义的属性?

BASE DIR 的绝对路径是什么?