My serializer, quite basic:
class TestSerializer(serializers.Serializer):
date_time = serializers.DateTimeField()
wanted to try out from shell but I get False
each time I try to check it for validation.
> import datetime
> s=TestSerializer({'date_time': datetime.datetime(year=2012,month=12,day=12)}
> s.data
{'date_time': datetime.datetime(2012, 12, 12, 0, 0)}
> s.is_valid()
False
> s.errors
{u'non_field_errors': [u'No input provided']}
Why is this? What is going on?
The .is_valid() method takes an optional raise_exception flag that will cause it to raise a serializers.ValidationError exception if there are validation errors.
The BaseSerializer class caches its data attribute on the object, but Serializer. data returns a copy of BaseSerializer. data every time it is accessed (via ReturnDict ).
We can validate the serializer by calling the method " is_valid() ". It will return the boolean(True/False) value. If the serializer is not valid then we can get errors by using the attribute "errors".
Serializers in Django REST Framework are responsible for converting objects into data types understandable by javascript and front-end frameworks. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.
I think you need to specify data explicitly:
s = TestSerializer(data={'date_time': datetime.datetime(year=2012,month=12,day=12)}
Otherwise it assumes that the first argument is a model instance but that's not the case here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With