DRF Response isn't working with class based views in Django

I am converting my function-based views to class-based views. Following the official documentation, I was getting errors using the Response imported from rest_framework. When using HttpResponse it's working fine. The error I am getting with Response is:

.accepted_renderer not set on Response

This is my view:

    
    def get(self, request):
        users = User.objects.all()
        serializer = UserSerializer(users, many=True)
        return Response(serializer.data) 

What could be the reason for this?

serializer:

    class Meta:
        model = User
        fields = '__all__'

Upvotes: 0

Views: 286

Answers (1)

Manoj Tolagekar
Manoj Tolagekar

Reputation: 1970

instead of this:

return Response(serializer.data) 

try this:

return Response(serializer.data, status=status.HTTP_200_OK) #Status is depends on your code

I think your serializer is not saved so that's why you are getting that error

    def get(self, request):
        users = User.objects.all()
        serializer = UserSerializer(users, data=request.data, many=True)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_200_OK) 

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

Final thing try this.

Upvotes: 1

Related Questions