I trial make Permission in CreateView

Viewed 128

I want to check if user in true editUser before open url and create post,

urls.py", line 13, in path('new/', PostCreateView.as_view(), name='new_post'), AttributeError: 'NoneType' object has no attribute '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)
2 Answers

Firstly your decorator has a small mistake, the indentation for return wrapper_func is wrong. Next to decorate class based views you should use method_decorator [Django docs] and specify the method of the class that should be decorated (Decorate the dispatch method if it needs to decorate the complete view):

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)

You should not decorate your class-based view with a decorator that returns a function, since then that function has no .as_view attribute.

Django has some tooling to apply a decorator to a function of the class-based view, we can however also implement a mixin and work with that 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')

Then we can use this for our view:

class SomeCreateView(EditUserPermissionPlugin, CreateView):
    # …
Related