在代码中,我试图实现用户的个人资料部分,以便他可以看到其个人资料并进行更新。在这里,我在对象级别上施加了一些限制,以便只有登录的用户才能看到他的个人资料。但是代码的自定义权限部分没有执行
请在下面找到代码
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
个人资料视图的代码
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)
答案 0 :(得分:2)
请注意,this section of the documentation
还要注意,为了运行实例级检查,视图代码应显式调用.check_object_permissions(request,obj)。如果您使用的是通用视图,则默认情况下会为您处理。
您需要在API方法中调用check_object_permissions(request, obj)
或从其中一个通用视图继承-RetrieveUpdateAPIView
似乎与您的API匹配。
class ProfileView(RetrieveUpdateAPIView):
authentication_classes = [TokenAuthentication]
permission_classes = [IsAuthenticated,IsProfilePermission]