I want to validate email id if already exists in the User model before registration
This is my serializer with validation
class RegistrationSerializer(serializers.Serializer):
username = serializers.CharField(max_length=100)
email = serializers.EmailField()
password = serializers.CharField(max_length=100)
def validate_email(self,attrs):
email=attrs['email']
print email
if email:
emailset = Q(email__icontains=email)
emailres = User.objects.filter(emailset)
if emailres:
msg = _('The email address is already taken')
raise serializers.ValidationError(msg)
else:
return attars
It is throwing error "TypeError:string indices must be integers"
email=attrs['email']
TypeError: string indices must be integers
I Guess you have upgraded or using DRF 3.x, so there is no more attrs
dict but the value instead. See field-level-validation
More over there is already a UniqueValidator. So I think you can just do:
class RegistrationSerializer(serializers.Serializer):
#...
email = serializers.EmailField(validators=[UniqueValidator(queryset=User.objects.all())])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With