-->

Add object level permission to generic view

2020-06-03 08:15发布

问题:

The situation is pretty simple: I'm writing a multi-user blog system. The system should prevent non-owner to edit or delete a blog post. In my view I use generic view.

class BlogUpdateView(UpdateView): ...

I know I should use @method_decorator to decorate dispatch method. However, most example is just @method_decorator(login_required) or model level permission. How can apply object level permission to check whether request.user is the author of this blog post? For example, I tried to use django-authority apps, and I have a BlogPermission class in this file. and I tried to define a method in this class e.g.

def blog_edit(self, ??, ??)

what should I put into this method?

And then call this like: @method_decorator(permission_required('blog_permission.blog_edit(???)'))

What should I pass in here?

Update: After read method_decorator code, I find it can only accept function without argument. I think that's why permission_required doesn't work here. But what's the work around about this?

Update solution:

In dispatch method, I check the user permission and then return HttpResponseForbidden() if the user does not meet the permission.

回答1:

You can do it using class-based-views:

class BlogEdit(UpdateView):
    model = Blog

    def dispatch(self, request, *args, **kwargs):
        if not request.user.has_perm('blog_permission.blog_edit'):
            return HttpResponseForbidden()
        return super(BlogEdit, self).dispatch(request, *args, **kwargs)

    # OR (for object-level perms)

    def get_object(self, *args, **kwargs):
        obj = super(BlogEdit, self).get_object(*args, **kwargs)
        if not obj.user == self.request.user:
            raise Http404 # maybe you'll need to write a middleware to catch 403's same way
        return obj