django getting Keyerror on updating nested serializer in DRF

y1aodyip  于 2022-12-14  发布在  Go
关注(0)|答案(1)|浏览(124)

I have two serializer AccountSerializerUserProfileSerializer . user in UserProfileSerializer is Foreingkey to AccountSerializer . When I try to update UserProfileSerializer I get key error confirm_password . That is actually validation in AccountSerializer . How to prevent this.

Serializer

class AccountSerializer(ModelSerializer):
    confirm_password = CharField(write_only=True)

    class Meta:
        model = Account
        fields = ["first_name", "last_name", "email", "password", "confirm_password"]
        extra_kwargs = {
            "password": {"write_only": True},
        }

    def validate(self, data):
        if data['password'] != data.pop("confirm_password"):
             raise ValidationError({"error": "Passwords donot match"})
        return data

    def create(self, validated_data):
        user = Account.objects.create_user(**validated_data)
        return user
class UserprofileSerializer(ModelSerializer):
    user = AccountSerializer()

    class Meta:
        model = UserProfile
        fields = "__all__"
    
    def update(self, instance, validated_data):
        user_data = validated_data.pop('user', None)
        print('user_data', user_data)
    
        account = instance.user
        account.first_name = user_data.get('first_name', account.first_name)
        account.last_name = user_data.get('last_name', account.last_name)
        account.email = user_data.get('email', account.email)
        account.save()
        return super().update(instance, validated_data)

Error

mcdcgff0

mcdcgff01#

I would change the validate(...) method as below,

def validate(self, data):
    data = super().validate(data)
    confirm_password = data.pop("confirm_password", None)
    if data.get("password") != confirm_password:
        raise ValidationError({"error": "Passwords donot match"})
    return data

相关问题