editing user details in python django rest framewo

2019-09-15 11:04发布

问题:

I need code for editing user details like first_name , last_name by using APIView Class based. THe serializers.py and views.py are given under but it is not making the changes according to the user details . i am passing token for user authentication. Any assistance will be appreciated.

Serializers.py

class UserEditSerializer(serializers.Serializer):
    email = serializers.EmailField(required=True)
    first_name = serializers.CharField(required=True)
    last_name = serializers.CharField(required=True)

    def update(self, validated_data, instance):

        instance.first_name = validated_data.get('first_name')
        instance.email = validated_data.get('email')
        instance.last_name = validated_data.get('last_name')
        instance.save()
        return instance()

Views.py

class UserEditProfile(APIView):
    authentication_classes = (authentication.TokenAuthentication,)
    permission_classes = (permissions.IsAuthenticated,)

    def get_object(self):
        return self.request.user

    def post(self, request):
        self.object = self.get_object()
        serializer = UserEditSerializer(data=request.data)
        if serializer.is_valid():
            self.object.save()
            return Response(serializer.data, status=status.HTTP_200_OK)
        else:
            return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST)

回答1:

How would the serializer know it must update a user if you don't provide it ?

    serializer = UserEditSerializer(data=request.data)

should be:

    serializer = UserEditSerializer(self.object, data=request.data)

Edit: Also, remove the () after return instance



回答2:

This view will work . Thanks Linovia

class UserEditProfile(APIView):
    authentication_classes = (authentication.TokenAuthentication,)
    permission_classes = (permissions.IsAuthenticated,)

    def post(self, request):
        obj = User.objects.get(id=request.user.id)
        serializer = UserEditSerializer(obj, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_200_OK)
        else:
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)