Django序列化器:验证未调用的函数

时间:2016-04-19 06:50:52

标签: python django django-forms django-views django-rest-framework

我正在尝试覆盖validate()函数以便serializers.is_valid()调用,但它不会被调用。

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)

当我调用is_valid()时,validate()函数内的print语句没有被执行。 我做错了什么?

2 个答案:

答案 0 :(得分:3)

我认为您没有收到任何print语句,因为没有调用validate函数。

如果其中一个字段中显示错误email,则validate函数无法调用,但由于您未将raise_exception=True作为参数传递给is_valid您没有收到这些错误,并且您认为is_valid没有运行。

您可以编写post方法,如下所示:

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

更新:如果要在验证不同字段后引发特定消息,可以在序列化程序中创建方法validate_<fieldname>

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

答案 1 :(得分:2)

我有同样的错误。尝试去

def run_validation(self, data):
...

代替

def validation(self, data):
...

这应该有效!