2

When trying to update a user the following message appears: "A user with this username already exists"

I have a standard Django User model and I have another profile template that extends.

How do I update this data, including the user profile.

Thank you.

Model

class Profile(User):
    nome_empresa = models.CharField(max_length=200)
    cnpj = models.CharField(max_length=15)

    def __str__(self):
        return self.nome_empresa

Serializer

class ProfileSerializer(serializers.ModelSerializer):
    class Meta:
        model = Profile
        fields = ('nome_empresa', 'cnpj')


class UserSerializer(serializers.ModelSerializer):
    profile = ProfileSerializer()
    class Meta:
        model = User
        fields = ('username', 'email', 'first_name', 'last_name', 'profile')

View

class usuario(APIView):


    def patch(self, request, format=None):

        user = UserSerializer(data=request.data)

        if user.is_valid():
            user.update(instance=request.user)
            return Response(HTTP_200_OK)

        return Response(user.errors)

1 Answer 1

6

django-rest-framework does not update nested serializers by default. To update the profile object, you need to override the serializer's update method.

class UserSerializer(serializers.ModelSerializer):
    profile = ProfileSerializer()

    def update(self, instance, validated_data):
        """Override update method because we need to update
        nested serializer for profile
        """
        if validated_data.get('profile'):
            profile_data = validated_data.get('profile')
            profile_serializer = ProfileSerializer(data=profile_data)

            if profile_serializer.is_valid():
                profile = profile_serializer.update(instance=instance.profile)
                validated_data['profile'] = profile

        return super(UserSerializer, self).update(instance, validated_data)

    class Meta:
        model = User
        fields = ('username', 'email', 'first_name', 'last_name', 'profile')
Sign up to request clarification or add additional context in comments.

3 Comments

what did you mean place_data is it typo?
An error has occurred: TypeError: update() missing 1 required positional argument: 'validated_data'
I was able to include the validate_data correctly, but the return is successful, nothing else is being saved in the database.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.