Prasanna Poojari
Prasanna Poojari

Reputation: 41

Custom object level DRF permission not working

In the code i am trying to implement profile part of the user where he can see his profile and update it. Here i apply some restriction at object level so that only a logged in user can see only his profile.but the custom permission part of the code is not executing

Please find the code below

from rest_framework import permissions  


class IsProfilePermission(permissions.BasePermission):
    def has_object_permission(self, request, view, obj):
        print("getting here") #checking whether code is coming here or not
        print(obj.__dict__) 
        print(request.user)
        return True

code for the profile view

class ProfileView(APIView):
        authentication_classes = [TokenAuthentication]
        permission_classes = [IsAuthenticated,IsProfilePermission]
    
        def get(self,request,*args,**kwargs):
            try:
                profile_obj = User.objects.get(pk=self.kwargs['pk'])
            except:
                return Response({"error":"Invalid profile"},status = status.HTTP_400_BAD_REQUEST )
            prof_serialize = ProfileSerializer(profile_obj)
            return Response(prof_serialize.data)
        
        def put(self,request,*args,**kwargs):
    
            try:
                profile_obj = User.objects.get(pk=self.kwargs['pk'])
            except:
                return Response({"error":"Invalid profile"},status = status.HTTP_400_BAD_REQUEST )
    
            serializer = ProfileSerializer(profile_obj,data=request.data)
            data = {}
            if serializer.is_valid():
                serializer.save()
                data['sucess']="profile successfully updated"
                return Response(data,status= status.HTTP_201_CREATED)
            else:
                return Response(serializer.errors,status = status.HTTP_400_BAD_REQUEST)
    

Upvotes: 0

Views: 382

Answers (1)

Iain Shelvington
Iain Shelvington

Reputation: 32304

Note, this section of the documentation

Also note that in order for the instance-level checks to run, the view code should explicitly call .check_object_permissions(request, obj). If you are using the generic views then this will be handled for you by default.

You need to either call check_object_permissions(request, obj) in your API methods or inherit from one of the generic views - RetrieveUpdateAPIView seems to match your API.

class ProfileView(RetrieveUpdateAPIView):
    authentication_classes = [TokenAuthentication]
    permission_classes = [IsAuthenticated,IsProfilePermission]

Upvotes: 2

Related Questions