Naggappan Ramukannan
Naggappan Ramukannan

Reputation: 2812

django rest permissions allow both IsAdmin and custom permission

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"

Upvotes: 5

Views: 7118

Answers (3)

esmail
esmail

Reputation: 657

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,)

Upvotes: 5

neverwalkaloner
neverwalkaloner

Reputation: 47364

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.

Upvotes: 4

Shehab ElDin
Shehab ElDin

Reputation: 614

you are using tuple syntax but you need comma to act as a tuple
replace
permission_classes = (Or(permissions.IsAdminUser,IsOwner))
with
permission_classes = (Or(permissions.IsAdminUser,IsOwner), )

Upvotes: 2

Related Questions