向通用视图添加对象级权限 [英] Add object level permission to generic view
问题描述
情况很简单:我正在编写一个多用户博客系统.系统应防止非所有者编辑或删除博客文章.在我看来,我使用通用视图.
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.
类 BlogUpdateView(UpdateView):...
class BlogUpdateView(UpdateView): ...
我知道我应该使用@method_decorator 来装饰调度方法.但是,大多数示例只是@method_decorator(login_required) 或模型级别的权限.如何应用对象级权限来检查 request.user 是否是这篇博文的作者?例如,我尝试使用 django-authority 应用程序,并且在此文件中有一个 BlogPermission 类.我试图在这个类中定义一个方法,例如
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?
然后这样调用:@method_decorator(permission_required('blog_permission.blog_edit(???)'))
我应该在这里传递什么?
What should I pass in here?
更新:在阅读method_decorator代码后,我发现它只能接受没有参数的函数.我认为这就是 permit_required 在这里不起作用的原因.但是有什么办法解决这个问题?
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?
更新解决方案:
在dispatch方法中,我检查用户权限,如果用户不满足权限则返回HttpResponseForbidden().
In dispatch method, I check the user permission and then return HttpResponseForbidden() if the user does not meet the permission.
推荐答案
您可以使用基于类的视图:
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
这篇关于向通用视图添加对象级权限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!