【问题标题】:I trial make Permission in CreateView我尝试在 CreateView 中创建权限
【发布时间】:2021-08-17 12:55:07
【问题描述】:

我想在打开 url 并创建帖子之前检查用户是否在真正的 editUser 中,

urls.py",第 13 行,在 path('new/', PostCreateView.as_view(), name='new_post'), AttributeError: 'NoneType' 对象没有属性 'as_view'

def notLoggedUsers(view_func):
    def wrapper_func(request,*args,**kwargs):
        if not request.user.profile.editUser:
            return redirect('index')
        else:
            return view_func(request,*args,**kwargs)
        return wrapper_func

@notLoggedUsers
class PostCreateView(LoginRequiredMixin, CreateView):
    model = Post
    template_name = 'crud/new_post.html'
    form_class =  PostForm

    def form_valid(self, form):
        form.instance.author = self.request.user 
        return super().form_valid(form)

【问题讨论】:

  • 你不应该装饰这个类,因为你的装饰器装饰了一个函数。

标签: django django-models django-views


【解决方案1】:

首先你的装饰器有一个小错误,return wrapper_func 的缩进是错误的。在装饰基于类的视图旁边,您应该使用method_decorator [Django docs] 并指定应该装饰的类的方法(如果需要装饰整个视图,请装饰dispatch 方法):

from django.utils.decorators import method_decorator


def notLoggedUsers(view_func):
    def wrapper_func(request, *args, **kwargs):
        if not request.user.profile.editUser:
            return redirect('index')
        else:
            return view_func(request, *args, **kwargs)
    return wrapper_func


@method_decorator(notLoggedUsers, name='dispatch')
class PostCreateView(LoginRequiredMixin, CreateView):
    model = Post
    template_name = 'crud/new_post.html'
    form_class =  PostForm

    def form_valid(self, form):
        form.instance.author = self.request.user 
        return super().form_valid(form)

【讨论】:

    【解决方案2】:

    你应该用一个返回一个函数的装饰器来装饰你的基于类的视图,因为那个函数没有.as_view属性。

    Django 有一些工具可以将装饰器应用于基于类的视图的函数,但是我们也可以实现一个 mixin 并使用该 mixin:

    from django.contrib.auth.mixins import UserPassesTestMixin
    from django.shortcuts import redirect
    
    class EditUserPermissionPlugin(LoginRequiredMixin, UserPassesTestMixin):
    
        def test_func(self):
            try:
                return self.user.profile.editUser
            except Profile.DoesNotExist:
                return False
    
        def handle_no_permission(self):
            return redirect('index')

    然后我们可以将它用于我们的视图:

    class SomeCreateView(EditUserPermissionPlugin, CreateView):
        # …

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-04
      • 1970-01-01
      • 2020-02-12
      • 2011-11-11
      • 2022-12-20
      相关资源
      最近更新 更多