git repo: django tutorial
I've been following the above django project that looks at creating at person to person chat. I've come across this part:
def message_list(request, sender=None, receiver=None):
...
elif request.method == 'POST':
print('posting')
data = JSONParser().parse(request)
print(data)
serializer = MessageSerializer(data=data)
print(serializer)
if serializer.is_valid():
serializer.save()
return JsonResponse(serializer.data, status=201)
class MessageSerializer(serializers.ModelSerializer):
sender = serializers.SlugRelatedField(many=False, slug_field='email', queryset=User.objects.all())
receiver = serializers.SlugRelatedField(many=False, slug_field='email', queryset=User.objects.all())
class Meta:
model = Message
fields = ['sender', 'receiver', 'message', 'timestamp']
What does "if serializer.is_valid():"
actually do? Is it checking that the data in the message matches the data in the user profile? I've never used serializers before and could use an explanation of it.
Thanks
The is_valid() method is used to perform validation for each field of the form, it is defined in Django Form class. It returns True if data is valid and place all data into a cleaned_data attribute.
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.
The HyperlinkedModelSerializer class is similar to the ModelSerializer class except that it uses hyperlinks to represent relationships, rather than primary keys. By default the serializer will include a url field instead of a primary key field.
You need to call is_valid
during deserialization process before write data to DB. is_valid
perform validation of input data and confirm that this data contain all required fields and all fields have correct types. If validation process succeded is_valid
set validated_data
dictionary which is used for creation or updating data in DB. Otherwise serializer's property errors
will contain information about errors in input data, and you can send this information as HTTP response in your view.
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