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)
1条答案
按热度按时间mcdcgff01#
I would change the
validate(...)
method as below,