ConAra
ConAra

Reputation: 301

How to check is user email is already saved in DB

I am trying to add email field to a model but before saving data I need to check whether the entered email already exists in DB or not. If not then save the data otherwise display error message. The current code is saving duplicate data. Can someone explain me what I am doing wrong here? I am new to Djanog DRF, please bear with me.

What I have done so far

Model.py

class Subscribe(models.Model):
    subscribe_email = models.EmailField(max_length=250)
    contacted_on = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.subscribe_email

Serializer.py

class SubscriberCreateSerializer(ModelSerializer):

    class Meta:
        model = Subscribe
        fields = ('subscribe_email', )

    def create(self, validated_data):
        instance = super(SubscriberCreateSerializer, self).create(validated_data)
        email = format(instance.subscribe_email)

        is_exists = Subscribe.objects.filter(subscribe_email=email).exists()
        if is_exists:
            raise ValidationError('Email exists')

        else:
            try:
                send_mail(
                    'Thank You for subscribing newsletter!',
                    'This mail is intended to confirm your successful submission for newsletter',
                    settings.EMAIL_HOST_USER,
                    [email, ],
                    fail_silently=False,
                )
            except BadHeaderError:
                raise ValidationError('Something went wrong, Please try again')

        return instance

Views.py

class SubscriberCreateAPIView(CreateAPIView):
    queryset = Contact.objects.all()
    serializer_class = SubscriberCreateSerializer

    def perform_create(self, serializer):
        serializer.save()

Edited:

I have found the solution. I changed the perform_create method Can someone please review this?

def perform_create(self, serializer):
    subscribe_email = serializer.validated_data.get('subscribe_email')
    is_exists = Subscribe.objects.filter(subscribe_email=subscribe_email).exists()
    if is_exists:
        raise ValidationError('Email exists')
    else:
        serializer.save()

Upvotes: 0

Views: 68

Answers (1)

Bary12
Bary12

Reputation: 1088

A simpler approach could be adding unique=True to the subscribe_email field.

subscribe_email = models.EmailField(max_length=250, unique=True)

When trying to create another subscription with the same email, Django Rest Framework will return a 400 status code with the following payload:

{
    "subscribe_email": [
        "subscribe with this subscribe email already exists."
    ]
}

Upvotes: 1

Related Questions