python - Django serializers: validate function not called -
i trying override validate()
function called serializers.is_valid()
, 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 invalid email. & blank email , password. ''' print 'hey in login' if data['email'] '': raise serializers.validationerror("email cannot empty.") if data['password'] '': raise serializers.validationerror("password cannot empty.") try: validate_email(data['email']) except validationerror: raise serializers.validationerror("the email not 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 else: return response(data.errors,status=status.http_400_bad_request)
while call is_valid()
, print statement inside validate()
function not getting executed. doing wrong?
i think not getting print
statements because validate
function not being called.
if there error in 1 of fields email
, validate
function won't called since didn't pass raise_exception=true
argument in is_valid
not getting errors , assume is_valid
not running.
you write post
method following:
def post(self, request): serializer = self.serializer(data=request.data) # following automatically raise exception if serialize data not valid serializer.is_valid(raise_exception=true) # if serializer valid
update: if want raise specific message after validating different fields, create method validate_<fieldname>
in serializer:
def validate_email(self, value): if value == '': raise serializers.validationerror("email cannot empty.") try: validate_email(value) except validationerror: raise serializers.validationerror("the email not valid email address.") return value
Comments
Post a Comment