Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rest framework serializer always returns False for is_valid

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?

like image 680
Salyangoz Avatar asked Dec 09 '13 17:12

Salyangoz


People also ask

What does serializer Is_valid () do?

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.

What does serializer data return?

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 ).

How do I know if my serializer is valid?

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".

What does a serializer return Django?

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.


1 Answers

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.

like image 198
Simeon Visser Avatar answered Oct 10 '22 23:10

Simeon Visser