将对象级别权限添加到通用视图 [英] Add object level permission to generic view

查看:90
本文介绍了将对象级别权限添加到通用视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

情况很简单:
我正在写一个多用户博客系统。该系统应防止非所有者编辑或删除博客文章。在我看来,我使用通用视图。

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):
...

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,??,??)

这个方法应该怎么做?

然后调用如下:
@method_decorator(permission_required('blog_permission.blog_edit(???)'))

我应该在这里传递什么?

What should I pass in here?

更新:读取method_decorator代码后,我发现它只能接受函数而没有参数。我认为这就是为什么permission_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?

更新解决方案:

在调度方法中,我检查用户权限如果用户不符合权限,则返回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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆