Django - 对象级权限和基于类的通用视图

发布于 2024-12-11 03:58:41 字数 841 浏览 0 评论 0原文

这是模型:

class Car(models.Model):
    user = models.ForeignKey(User, related_name='cars')
    name = models.CharField(max_length=64)

Url 模式是这样的:

url(r'^car/(?P<pk>\d+)/$', login_required(CarDetails.as_view()), name='car_details)

和视图:

class CarDetail(DetailView):
    context_object_name = 'car'
    template_name = 'my_app/car_details.html'
    model = models.Car

    def get_object(self, *args, **kwargs):
        car = super(CarDetail, self).get_object(*args, **kwargs)
        if car.user != self.request.user:
            raise PermissionDenied()
        else:
            return car

这工作正常,但在每个类中我都必须重写 get_object 以防止用户弄乱其他人的对象。这包括对我拥有的每个模型进行编辑和删除,这严重违反了 DRY 原则。

有更好的方法吗?也许类似于 login_required 装饰器?

This is the model:

class Car(models.Model):
    user = models.ForeignKey(User, related_name='cars')
    name = models.CharField(max_length=64)

Url pattern goes something like this:

url(r'^car/(?P<pk>\d+)/

And view:

class CarDetail(DetailView):
    context_object_name = 'car'
    template_name = 'my_app/car_details.html'
    model = models.Car

    def get_object(self, *args, **kwargs):
        car = super(CarDetail, self).get_object(*args, **kwargs)
        if car.user != self.request.user:
            raise PermissionDenied()
        else:
            return car

This works fine, but in every class I have to override get_object to prevent user to mess with someone else's objects. This includes editing and deleting for every model I have and this is serious violation of DRY principle.

Is there a better way to do this? Something like login_required decorator maybe?

, login_required(CarDetails.as_view()), name='car_details)

And view:

This works fine, but in every class I have to override get_object to prevent user to mess with someone else's objects. This includes editing and deleting for every model I have and this is serious violation of DRY principle.

Is there a better way to do this? Something like login_required decorator maybe?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

阳光的暖冬 2024-12-18 03:58:41

定义基类(或混合)并使用继承怎么样?

class CurUserOnlyDetailView(DetailView):
    def get_object(self, *args, **kwargs):
        obj = super(CurUserOnlyDetailView, self).get_object(*args, **kwargs)
        if obj.user != self.request.user:
            raise PermissionDenied()
        else:
            return obj

class CarDetail(CurUserOnlyDetailView):
    context_object_name = 'car'
    template_name = 'my_app/car_details.html'
    model = models.Car

# another view, no DRY violation
class BikeDetail(CurUserOnlyDetailView):
    context_object_name = 'bike'
    template_name = 'my_app/bike_details.html'
    model = models.Bike

What about definig base class (or mixin) and using inheritance?

class CurUserOnlyDetailView(DetailView):
    def get_object(self, *args, **kwargs):
        obj = super(CurUserOnlyDetailView, self).get_object(*args, **kwargs)
        if obj.user != self.request.user:
            raise PermissionDenied()
        else:
            return obj

class CarDetail(CurUserOnlyDetailView):
    context_object_name = 'car'
    template_name = 'my_app/car_details.html'
    model = models.Car

# another view, no DRY violation
class BikeDetail(CurUserOnlyDetailView):
    context_object_name = 'bike'
    template_name = 'my_app/bike_details.html'
    model = models.Bike
神爱温柔 2024-12-18 03:58:41

正如 DrTyrsa 在他的答案中提出的那样,解决方案或多或少很简单,只有一点点不同。我创建了继承 object 的基类 CurUserOnly,而不是 DetailView (我想将此类与 DeleteView 一起使用,并且UpdateView 也是如此),现在 CarDetail 继承 CurUserOnlyDetailViewCarDelete 继承CurUserOnlyDeleteView 等等...

有趣的是,我之前尝试过这个,但是没有成功,因为我忘记了 python 的 MRO 和 DetailView 是继承列表中的第一个,而 CurUserOnly 应该是!

最后,这是 CurUserOnly 类:

class CurUserOnly(object):
    def get_object(self, *args, **kwargs):
        obj = super(CurUserOnly, self).get_object(*args, **kwargs)
        user_attribute = getattr(self, 'user_attribute', 'user')
        user = obj
        for part in user_attribute.split('.'):
            user = getattr(user, part, None)
        if user != self.request.user:
            raise PermissionDenied()
        else:
            return obj

如果我有一个与用户没有直接联系的模型,我需要做的就是添加 user_attribute 字段。例如,如果我有模型 Tyre ,其中带有 Car 的外键,则其删除视图将如下所示:

class TyreDelete(CurUserOnly, DeleteView):
    model = models.Tyre
    user_attribute = 'car.user'

此答案作为 编辑问题Django - 对象级 premission 和基于类的通用视图 OP del-boy 根据 CC BY-SA 3.0。

The solution was more-or-less simple as DrTyrsa proposed in his answer, with one little difference. I created base class CurUserOnly that inherits object, instead of DetailView (I wanted to use this class with DeleteView and UpdateView, too) and now CarDetail inherits CurUserOnly and DetailView, CarDelete inherits CurUserOnly and DeleteView and so on...

Funny thing is that I tried this before, but it didn't work because I forgot python's MRO and DetailView was first in inheritance list when CurUserOnly should be!

In the end, here is CurUserOnly class:

class CurUserOnly(object):
    def get_object(self, *args, **kwargs):
        obj = super(CurUserOnly, self).get_object(*args, **kwargs)
        user_attribute = getattr(self, 'user_attribute', 'user')
        user = obj
        for part in user_attribute.split('.'):
            user = getattr(user, part, None)
        if user != self.request.user:
            raise PermissionDenied()
        else:
            return obj

And if I have a model that does not have direct contact to user all I need to do is add user_attribute field. For example, if I have model Tyre with ForeignKey to Car its DeleteView would look like this:

class TyreDelete(CurUserOnly, DeleteView):
    model = models.Tyre
    user_attribute = 'car.user'

This answer was posted as an edit to the question Django - object level premission and class based generic views by the OP del-boy under CC BY-SA 3.0.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文