Skip to content Skip to sidebar Skip to footer

Django: A More Dry Way To Prevent Edit/delete Of Objects?

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

Solution 1:

Here is my working example.

1) QuerySet

classPermissionQuerySet(models.query.QuerySet):
    defeditable_by(self, user):
        return self.filter(user=user)

    defviewable_by(self, user):
        return self.filter(user=user)

2) Managers

classPermissionManager(models.Manager):defget_query_set(self):
        return PermissionQuerySet(self.model)

    defeditable_by(self, user, *args):
        returnself.get_query_set().editable_by(user, *args)

    defviewable_by(self, user, *args):
        returnself.get_query_set().viewable_by(user, *args)

3) Models

classMyModel(models.Model):
    ...
    objects =PermissionManager()

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.

This is working sample:

classMyUpdateView(UpdateView):defpost(self, request, *args, **kwargs):
        self.request = request
        super(MyUpdateView, self).post(request, *args, **kwargs)

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

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

Solution 2:

Pass an additional parameter to get_object_or_404:

reward = get_object_or_404(Reward, pk=reward_id, owner=request.user)

Post a Comment for "Django: A More Dry Way To Prevent Edit/delete Of Objects?"