I have problem with Django. I did all as was written in the tutorial but when I check is_valid on serializer there is always false.
Here is my code:
models.py
from django.db import models
class User(models.Model):
userId = models.CharField(max_length=100)
email = models.EmailField()
serializers.py
from .models import User
from rest_framework import serializers
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'userId', 'email')
And then I run python manage.py shell
. Then I use commands like:
from belmondoapp.models import User
from belmondoapp.serializers import UserSerializer
u = User(userId="user", email="[email protected]")
s = UserSerializer(data=u)
s.is_valid()
And it always returns False... Why? What did I wrong?
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".
Validation in Django REST framework serializers is handled a little differently to how validation works in Django's ModelForm class. With ModelForm the validation is performed partially on the form, and partially on the model instance. With REST framework the validation is performed entirely on the serializer class.
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.
It is not necessary to use a serializer. You can do what you would like to achieve in a view. However, serializers help you a lot. If you don't want to use serializer, you can inherit APIView at a function-based-view.
After having the same problem I'd like to highlight the solution offered by @Andrea Corbellini in the comments section:
print(s.errors)
Will return a dictionary containing the fields: reason for fail
. In my case this looked like:
{
'start_date': [ErrorDetail(string='Expected a date but got a datetime.', code='datetime')],
'end_date': [ErrorDetail(string='Expected a date but got a datetime.', code='datetime')],
'client': [ErrorDetail(string='Incorrect type. Expected pk value, received Client.', code='incorrect_type')]
}
I found this absolutely invaluable.
s = UserSerializer(data=u)
should be:
s = UserSerializer(data={"userId"="user", "email"="[email protected]"})
The serialization process (from the Model to the dictionary) doesn't require a call to is_valid
:
s = UserSerializer(instance=u)
s.data
The deserialization process (from dict to Model) doesn't accept Model:
s = UserSerializer(data={"userId"="user", "email"="[email protected]"})
s.is_valid()
s.validated_data
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