我正在尝试重写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语句未得到执行。我究竟做错了什么?
最佳答案
我认为您没有收到任何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
UPDATE :如果要在验证不同字段之后引发特定消息,则可以在序列化器中创建
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
关于python - Django序列化器: validate function not called,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36710598/