Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why DjangoRF serializer is_valid is false?

My class

class SprintSerializer(serializers.ModelSerializer):

    links = serializers.SerializerMethodField()

    class Meta:
        model = Sprint
        fields = ('id', 'name', 'description', 'end', 'links', )

In my shell,I populated a serializer with data

serializer = SprintSerializer(data=({'name':'JHolmes','description':'ambassador','end':'2019-01-27T15:17:10.375877'}))

Then

serializer.data
{'name': 'JHolmes', 'description': 'ambassador', 'end': '2019-01-27T15:17:10.375877'}
serializer.validated_data
{}
serializer.is_valid()
False

Why is an instance serializer False? EDIT As Berry pointed out,data format was wrong

serializer.errors
{'end': [ErrorDetail(string='Date has wrong format. Use one of these formats instead: YYYY[-MM[-DD]].', code='invalid')]}

Solved issue

'end':'2019-01-27'
serializer.is_valid()
True
like image 903
Richard Rublev Avatar asked May 24 '18 12:05

Richard Rublev


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.

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

Is it necessary to use Serializers in 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.

What is difference between serializer and ModelSerializer?

The ModelSerializer class is the same as a regular Serializer class, except that: It will automatically generate a set of fields for you, based on the model. It will automatically generate validators for the serializer, such as unique_together validators. It includes simple default implementations of .


1 Answers

Just use below code to find out validation errors:

print(serializer.errors)
like image 170
Ehsan Barkhordar Avatar answered Nov 15 '22 17:11

Ehsan Barkhordar