Skip to content Skip to sidebar Skip to footer

Django Rest Framework - Deny User From Push When User Is Not Object Owner

At the moment i have permissions set which prevent a user from GET, DELETE and PUT if they are not the Object Owner of Stock. But for some reason, the permissions do not work when

Solution 1:

When you POST to v1/notes/ the only permission check that will run is has_permission. There's no existing instance being referred to in the URL, so get_object isn't called on the view, and the has_object_permission check isn't called (there's no instance to call it with.)

What you need for this case is to enforce validation on the serializer class that ensures that the stock value must correspond to a Stock instance that is owned by the user.

Something along these lines...

defvalidate_stock(self, value):
    stock = Stock.objects.get(pk=value)
    user = self.context['request'].user
    ifnot stock.user == user:
        raise serializers.ValidationError(...)
    return value

Post a Comment for "Django Rest Framework - Deny User From Push When User Is Not Object Owner"