[Answered ]-Djago rest framework โ€“ username/email already exsists when trying to update user info

1๐Ÿ‘

โœ…

You have to pass the instance to UpdateUserSerializer when initializing it, otherwise is_valid() will think that you are creating a new object, hence the error.

So you can do something like:

@api_view(['PATCH'])
@permission_classes([IsAuthenticated])
def update_user(request):
    if request.method == 'PATCH':
        user = request.user
        serializer = UpdateUserSerializer(
            data=request.data, instance=user, context={'request': request}
        )

        data = {}

        if serializer.is_valid():
            user = serializer.save()
            data['user'] = UserSerializer(user).data
        else:
            data = serializer.errors
        return Response(data)

save() will call update() for you when there is an instance in the serializer so no need to explicitly call it.

๐Ÿ‘คBrian Destura

Leave a comment