Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django serializers: validate function not called

I am trying override validate() function to be called by serializers.is_valid(), but its not getting called.

serializer.py

class LoginSerializer(serializers.Serializer):
    email = serializers.EmailField(max_length=255,required=True)
    password = serializers.CharField(max_length=128,required=True)


    def validate(self,data):
       '''
       Check for invalid email.
       & blank email and password. 
       '''

       print 'hey i am in login'

       if data['email'] is '':
           raise serializers.ValidationError("Email cannot be empty.")
       if data['password'] is '':
          raise serializers.ValidationError("Password cannot be empty.")
       try:
          validate_email(data['email'])
       except ValidationError:
          raise serializers.ValidationError("The email is not a valid email address.")
       return data

views.py

class LoginAPI(APIView):
    permission_classes = (permissions.AllowAny,)
    serializer = LoginSerializer

    def post(self, request):
       data = self.serializer(data=request.data)
       if data.is_valid():
          #do something
       else:
           return Response(data.errors,status=status.HTTP_400_BAD_REQUEST)

while i call is_valid(), the print statement inside validate() function is not getting executed. what am i doing wrong?

like image 621
aman Avatar asked Apr 19 '16 06:04

aman


2 Answers

I think you are not getting any print statements because validate function is not being called.

If there is an error in one of the fields say email, validate function won't be called but since you didn't pass raise_exception=True as argument in is_valid you are not getting those errors and you assume that is_valid is not running.

You could write the post method as following:

def post(self, request):
   serializer = self.serializer(data=request.data)

   # following will automatically raise an exception if the serialize data is not valid
   serializer.is_valid(raise_exception=True)

   # do something if the serializer is valid

UPDATE: If you want to raise specific message after validating different fields, you could create a method validate_<fieldname> in serializer:

def validate_email(self, value):

    if value == '':
        raise serializers.ValidationError("Email cannot be empty.")

    try:
        validate_email(value)
    except ValidationError:
        raise serializers.ValidationError("The email is not a valid email address.")

    return value
like image 113
AKS Avatar answered Sep 21 '22 22:09

AKS


I had the same error. Try to go with

def run_validation(self, data):
...

instead of

def validation(self, data):
...

this should work!

like image 30
Perino Avatar answered Sep 17 '22 22:09

Perino