Reputation: 1684
Very strange but whenever I try to use any of my DRF serializers to serialize an object, like for instance:
me = CustomUser.objects.all()[0]
serializer = CustomUserSerializer(me)
serializer.is_valid()
# --> False
print(serializer.errors)
# {"non_field_errors": ["No input provided"]}
and this happens with totally different serializers and various objects.
However, if I use a class-based view (that indirectly uses the same serializers and the same objects), I am able to receive a JSON response with the data serialized as expected. Said differently, calling an endpoint linked to this view
class CustomUserList(generics.ListAPIView):
queryset = CustomUser.objects.all()
serializer_class = CustomUserSerializer
will indeed return a JSON representation of all the CustomUsers
in the database.
There must be something I did not quite understand.
Upvotes: 6
Views: 4314
Reputation: 41671
Django REST Framework allows you to serialize an object by passing it into a serializer through the instance
keyword (or the first positional argument). From there, you just need to call data
on it. This is all covered in the serializing objects part of the documentation.
me = CustomUser.objects.all()[0]
serializer = CustomUserSerializer(me)
serializer.data
You only need to call is_valid
when you are deserializing data into an object. The error you are getting ("No input provided") is because you are trying to validate the data to be deserialized, but you are passing no data in.
Upvotes: 13