Add object level permission to generic view

后端 未结 1 2023
余生分开走
余生分开走 2021-02-08 19:57

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.

1条回答
  •  名媛妹妹
    2021-02-08 20:41

    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
    

    0 讨论(0)
提交回复
热议问题