0

I have a front end built with Angular 9 and a django rest api to capture the email for a subscription form.

I would to validate the entry from the frontend to make sure it does not exist in the database before it is saved if it does not exsit.

here is the model:

class Email(models.Model):
    email = models.EmailField(max_length=50)

    def __str__(self):
        return str(self.email)

The view set:

class EmailViewSet(viewsets.ModelViewSet):
    queryset = models.Email.objects.all() 
    serializer_class = serializers.EmailSerializer

    def create (self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        return Response(serializer.data,status=status.HTTP_201_CREATED)

    def perform_create(self,serializer):
        queryset = models.Email.objects.filter(email=request.data)
        if queryset.exists():
            raise ValidationError('Email exist!')
        serializer.save(email=request.data)

1 Answer 1

3

You can simply mark the email field as unique=True [Django-doc]:

class Email(models.Model):
    email = models.EmailField(max_length=50, unique=True)

    def __str__(self):
        return self.email

The serializers in the Django REST framework take uniqness into acount and will check if an Email with the given email already exists. Furthermore the uniqness is also enforced at the database level, so normally if the database works properly it is impossible to create a second record with the same email value.

In the serializer you can specify the error message with:

from rest_framework import serializers

class EmailSerializer(ModelSerializer):
    email = serializers.EmailField(validators=[
        UniqueValidator(
            queryset=Email.objects.all(),
            message='Such email address already exists'
        )]
    )

    class Meta:
        model = Email
        fields = '__all__'
Sign up to request clarification or add additional context in comments.

2 Comments

Ok. thats nice and how would i return the error message on the angular front end for an end user @WillemVanOnsem
@namdi: you can specify the message in the serializer, see edit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.