Django DRF Update User

2019-07-04 00:12发布

问题:

Im trying to create an api using the Django-Rest-Framework (DRF) to CRUD a User. I have managed to create and read a user, but for some reason update will not work. It seems to be that it is trying to create a User rather than update it as it responds with a 'username already exists' error message. When I try passing an email that isn't already in the database it just creates a new user. Does anyone know why this is happening?

Here is my User Serializer:

class UserSerializer(FriendlyErrorMessagesMixin, serializers.ModelSerializer):
    password = serializers.CharField(
        max_length=128,
        min_length=8,
        write_only=True
    )

    class Meta:
        model = User
        fields = ('username',
                  'email',
                  'password',
                  'name',
                  'house_number',
                  'address_line_one',
                  'address_line_two',
                  'address_line_three',
                  'city',
                  'postcode',
                  'phone_number')
        read_only_fields = ('date_created', 'date_modified', 'username')

    def update(self, instance, validated_data):

        password = validated_data.pop('password', None)

        for (key, value) in validated_data.items():
            setattr(instance, key, value)

        if password is not None:
            instance.set_password(password)

        instance.save()

        return instance

and here is my view:

class UserRetrieveUpdateAPIView(RetrieveUpdateAPIView):
    permission_classes = (IsAuthenticated,)
    serializer_class = UserSerializer

    def retrieve(self, request, *args, **kwargs):
        serializer = self.serializer_class(request.user)
        return Response(serializer.data, status=status.HTTP_200_OK)

    def update(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data, partial=True)
        serializer.is_valid(raise_exception=True)
        serializer.save()

        return Response(serializer.data, status=status.HTTP_200_OK)

回答1:

In the view, you should pass the Serializer an instance to update as the first argument, otherwise a new object will be created.

To update the authenticated user, you would do:

def update(self, request, *args, **kwargs):
    serializer = self.serializer_class(request.user, data=request.data, partial=True)
    serializer.is_valid(raise_exception=True)
    serializer.save()
    return Response(serializer.data, status=status.HTTP_200_OK)

In general, you may want to use or override the get_object method (from GenericAPIView) to retrieve the correct instance ; instead of re-implementing both retrieve and update.