Home > Software engineering >  getting Keyerror on updating nested serializer in DRF
getting Keyerror on updating nested serializer in DRF

Time:12-11

I have two serializer AccountSerializer UserProfileSerializer. 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 enter image description here

CodePudding user response:

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
  • Related