I have a views.py as below,
from webapi.permissions import IsOwner
class MemberDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = members.objects.all()
serializer_class = MemberSerializer
permission_classes = (permissions.IsAdminUser,IsOwner)
And the following is custom permission to check if the user is ower of object in webapi.permissions,
class IsOwner(permissions.BasePermission):
def has_object_permission(self, request, view, obj):
return obj.owner == request.user
Now the issue is it is check if he is a admin user and gives permissions to update / delete, But if the owner is the user it should actually give permission to edit he data but in this case it is failing.
On seeing the question "Django Rest Framework won't let me have more than one permission" I tried as below also still it did not work when I use Or,
class MemberDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = members.objects.all()
serializer_class = MemberSerializer
permission_classes = (Or(permissions.IsAdminUser,IsOwner))
If I use Or it is failing with error during run time as "'Condition' object is not iterable"
Since DRF 3.9, you can use the logical bitwise operators |
and &
(~
was added in 3.9.2).
As outlined in the docs you would just need
permission_classes = (permissions.IsAdminUser|IsOwner,)
If you need give edit permissions for admin and owner users only, you can implement custom permission class:
class IsOwnerOrAdmin(permissions.BasePermission):
def has_object_permission(self, request, view, obj):
if request.method in permissions.SAFE_METHODS:
return True
return obj.owner == request.user or request.user.is_admin
And use only this one in the view:
permission_classes = [IsOwnerOrAdmin]
This method is documented here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With