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)