Melissa Stewart
Melissa Stewart

Reputation: 3615

AssertionError: Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'NoneType'>`

I've the following room object which has Users as members.

class Room(Base):
    name = models.CharField(db_index=True, unique=True, max_length=255)
    members = models.ManyToManyField(User, blank=True)

I'm trying to find the Room that has only two specific members,

if Room.objects.filter(members__id=first.id).filter(members__id=second.id).exists():
                    rooms = Room.objects.filter(members__id=first.id).filter(members__id=second.id)
                    for room in rooms:
                        print(room.members.count)
                        if room.members.count == 2:
                            return Response({"Success": RoomSerializer(room).data}, status=status.HTTP_200_OK)

I know that there exists a Room object which has only two members. But I end up getting this error,

AssertionError: Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'NoneType'>`

Any help appreciated.

Upvotes: 1

Views: 9498

Answers (2)

Borut
Borut

Reputation: 3364

QuerySet count() is a method (type(room.members.count) returns <class 'method'>) and should be called as such. Just change

room.members.count

to

room.members.count()

and it should work as expected.

Upvotes: 2

ruddra
ruddra

Reputation: 51988

As the exception said, at the end of the view, always return a response. In you current code, if the logics does not match, then it returns None.So, update the code like this:

if Room.objects.filter(members__id=first.id).filter(members__id=second.id).exists():
                rooms = Room.objects.filter(members__id=first.id).filter(members__id=second.id)
                for room in rooms:
                    print(room.members.count)
                    if room.members.count == 2:
                        return Response({"Success": RoomSerializer(room).data}, status=status.HTTP_200_OK)
return Response({"Failed": True}, status=status.HTTP_400_BAD_REQUEST) # <-- Return a bad request maybe at the end if all logic fails

Upvotes: 1

Related Questions