Django:防止编辑/删除对象的更干燥方式? [英] Django: A more DRY way to prevent edit/delete of objects?

查看:135
本文介绍了Django:防止编辑/删除对象的更干燥方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

阅读权限Django文档后,我仍然感到困惑。
我想阻止访问用户编辑或删除他们不拥有的对象。
我以这种方式点它,它的作品:

After reading the permission Django documentation, I'm still confused. I'd like to prevent access for user to edit or delete objects they didn't own. I dit it this way and it works:

在views.py:

def deleteReward(request, reward_id):
    reward = get_object_or_404(Reward, pk=reward_id)
    if reward.owner.user != request.user: # if the user linked to the reward is not the current one
        raise Exception("This reward is not yours, you can't delete it !")
    #...

但是我认为这不干净,而且DRY有两个原因:

But I think this isn't clean and DRY for two reasons:


  1. 在每个editStuff和deleteStuff视图中,我必须编写相同的代码段。

  1. In each editStuff and deleteStuff views, I'll have to write the same portion of code.

我正在写一个API与Tastypie,如果权限逻辑在视图中,我将无法重新使用它。处理最好的方法似乎是将API权限映射到Django权限(但是我在视图中写的代码与权限无关)。

I'm currently writing an API with Tastypie, and if the permission logic is in a view, I won't be able to re-use it. The best way to deals with seems to be to map the API permission with the Django permissions (but the code I wrote in my view has nothing to do with permissions).

你能帮我找到正确的方法吗?
非常感谢。

Could you help me to find the right way to do? Thanks a lot.

推荐答案

这是我的工作示例。

1)QuerySet

1) QuerySet

class PermissionQuerySet(models.query.QuerySet):
    def editable_by(self, user):
        return self.filter(user=user)

    def viewable_by(self, user):
        return self.filter(user=user)

2)经理

class PermissionManager(models.Manager):
    def get_query_set(self):
        return PermissionQuerySet(self.model)

    def editable_by(self, user, *args):
        return self.get_query_set().editable_by(user, *args)

    def viewable_by(self, user, *args):
        return self.get_query_set().viewable_by(user, *args)

3)模型

class MyModel(models.Model):
    ...
    objects = PermissionManager()

这个程序蟑螂与基于类的观点完美地工作。我看到你使用TastyPie。我从来没有使用过它,但它似乎也使用基于类的视图。

This approach works perfectly with class based views. I see you using TastyPie. I never used it before but it seems it's uses class based views too.

这是工作示例:

class MyUpdateView(UpdateView):
    def post(self, request, *args, **kwargs):
        self.request = request
        super(MyUpdateView, self).post(request, *args, **kwargs)

    def get_query_set(self):
        queryset = super(MyUpdateView, self).get_query_set()
        queryset = queryset.editable_by(self.request.user)
        if not queryset.exists():
            raise Exception("This reward is not yours, you can't delete it !")
        return queryset

我想你可以想象如何在CreateView,DeleteView中使用这种方法。而且我觉得在TastyPie中很容易实现。

I think you can imagine how to use this approach in CreateView, DeleteView. And i think it is easy to implement this in TastyPie.

这篇关于Django:防止编辑/删除对象的更干燥方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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