简体   繁体   中英

How to update user data using django and rest framework?

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)

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM