Add object level resolution to general view

The situation is quite simple: I am writing a multi-user blog system. The system should prevent the owner from editing or deleting a blog entry. In my opinion, I use the general view.

BlogUpdateView class (UpdateView): ...

I know that I should use @method_decorator to decorate the submit method. However, in most cases this is simply @method_decorator (login_required) or model level permission. How can I apply object-level permission to check if request.user is the author of this blog post? For example, I tried using django-authority applications, and I have the BlogPermission class in this file. and I tried to define a method in this class, for example.

def blog_edit(self, ??, ??)

what should i use in this method?

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

What am I supposed to go through here?

Update: after reading the method_decorator code, I believe that it can only accept a function without an argument. I think that why permission_required does not work here. But what works about it?

Update solution:

In the submit method, I check the permission of the user, and then return HttpResponseForbidden () if the user does not respond to the permission.

+7
source share
1 answer

You can do this 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 same way return obj 
+11
source

All Articles