pythondjango-rest-framework

Getting error in .is_valid() method in DRF


I am tyring to create a User Registration API, but I am getting an error when using a POST request in the following view:

@action(methods=['GET', 'POST'], detail=False, permission_classes=[AllowAny])
def users(self, request):
    if request.method == 'GET':
        queryset = User.objects.all()
        serializer = UserSerializer(queryset, many=True)
        return Response(serializer.data, status=status.HTTP_201_CREATED)

    elif request.method == 'POST':
        queryset = User.objects.all()
        serializer = UserSerializer(queryset, many=True)
        if serializer.available():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

The exception returned is the following:

Cannot call `.is_valid()` as no `data=` keyword argument was passed when 
instantiating the serializer instance.

Solution

  • You pass an object or a queryset to a serializer when you want to serialize it, so it's fine in your GET method.

    However, when you want to create an object using a serializer, you have to pass the data parameter before calling .is_valid(), and only then you can create your new objects withsave(). This is because the serializer needs to validate the data given to him before he does any save.

    What you should do is the following:

        [...]
        elif request.method == 'POST':
            serializer = UserSerializer(data=request.data, many=True)
            if serializer.is_valid():
                serializer.save()
                return Response(serializer.data, status=status.HTTP_201_CREATED)
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)