Ali Aref
Ali Aref

Reputation: 2412

email already exists while updating user in django rest framework

I was updating the User when faced email already exists crossed my way. how ever i could use the extra_kwargs to overcome the email already exists or phone already exists issue. and then using from django.core.validators import EmailValidator in extra_kwargs as "email": {"validators": [EmailValidator]}.. bring back my email field validations.

but that don't seems as a real solution. As we are just updating the existing model object.. why It's behaving like we are creating a new one.

I think there should be something as defining update or partial_update or i don't know what ever.. is there any other solutions for this ??

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = "id", "full_name", "gender", "phone", "email", "date_of_birth"
        extra_kwargs = {
            # "phone": {"validators": []},
            # "email": {"validators": [EmailValidator]},
        }

Upvotes: -1

Views: 2855

Answers (1)

Mahrus Khomaini
Mahrus Khomaini

Reputation: 814

As far as i know, by default email field in User django is not unique, if want to change unique in database, you can use AbstractUser, it will automatic detect unique in your serializer, and cannot save user with already exists email.

Then assume, we are not using AbstracUser, so we need to validate unique email manually in our serializer. We can use 2 ways:

1. UniqueValidator

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ["id", "full_name", "gender", "phone", "email", "date_of_birth"]
        extra_kwargs = {
            "email": {
                "validators": [
                    EmailValidator
                    UniqueValidator(
                       queryset=User.objects.all(),
                       message="This email already exist!"
                    )
                ]
            },
        }

2. Validate Email Manually: In our serializer, just add function to validate email

def validate_email(self, value):
    if User.objects.filter(email=value).exists():
       raise serializers.ValidationError("This email already exists!.")
    return value

CMIIW

Upvotes: 3

Related Questions