Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django rest framework email validation

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

like image 259
Naresh Avatar asked Dec 14 '22 15:12

Naresh


1 Answers

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())])
like image 166
Todor Avatar answered Jan 25 '23 01:01

Todor