knkzlgc knkzlgc - 3 months ago 22
Python Question

How to create permission for specific rules in Django Rest Framework?

I want to arrange permission like that each user can edit his own profile. Just super user can edit all profile. What I need to add permissions.py ? Thank you.

views.py

class UserViewSet(mixins.ListModelMixin,
mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
generics.GenericAPIView):

queryset = User.objects.all()
serializer_class = UserSerializer
permission_classes = [IsAuthenticated]
authentication_classes = (JSONWebTokenAuthentication, )


permissions.py

class IsOwnerOrReadOnly(BasePermission):

message = '!!'
my_safe_method = ['GET', 'PUT']

def has_permission(self, request, view):
if request.method in self.my_safe_method:
return True
return False

def has_object_permission(self, request, view, obj):
# member .0 Membership.objects.get(user=request.user)
# member.is_active
if request.method in SAFE_METHODS:
return True
return obj.user == request.user

Answer

Write your own permission

class IsObjectOwner(BasePermission):
        message = "You must be the owner of this object."
        my_safe_methods = ['GET', 'PUT', 'PATCH', 'DELETE']

    def has_permission(self, request, view):
        if request.method in self.my_safe_methods:
            return True
        return False

    def has_object_permission(self, request, view, obj):
        if request.user.is_superuser:
            return obj
        else:
            return obj.user_id == request.user

and then in the view add it in permission_classes

class ObjectDetailView(RetrieveUpdateDestroyAPIView):
    permission_classes = [IsObjectOwner, permissions.IsAuthenticated]
Comments