Add object level permission to generic view

為{幸葍}努か 提交于 2019-12-09 05:36:56

问题


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


来源:https://stackoverflow.com/questions/10326938/add-object-level-permission-to-generic-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!