django-rest-framework: Cannot call `.is_valid()` a

2019-03-25 04:41发布

问题:

I've the following model:

class NoteCategory(models.Model):
    title = models.CharField(max_length=100, unique=True)

    def __unicode__(self):
        return '{}'.format(self.title)

class PatientNote(models.Model):
    category = models.ForeignKey(NoteCategory)
    patient = models.ForeignKey(Patient)
    description = models.CharField(max_length=500)
    created_at = models.DateTimeField(auto_now_add=True)

    def __unicode__(self):
        return '{}'.format(self.description)

And the following serializer:

class PatientNoteSerializer(serializers.ModelSerializer):
    class Meta:
        model = PatientNote

I just want to make a POST on the PatientNote. The GET works and also the POST on other models works properly:

class PatientNoteViewSet(APIView):
    queryset = PatientNote.objects.all()


    def post(self, request, format=None):
        if not request.auth:
            return Response({})
        token = Token.objects.filter(key=request.auth)[0]
        user = token.user

        serializer = PatientNoteSerializer(request.data)
        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)

The request.data is a QueryDict, i.e.,

<QueryDict: {u'category': [u'1'], u'patient': [u'1'], u'description': [u'da rest']}>

It would be able to populate the two FKs, patient and category, through their IDs and the description is a simple text.

The POST request is the following one (that works with other models):

Anyway, the POST response is 500 with the following error:

AssertionError at /api/notes/

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

The error is the same if I try to use it in the python shell.

回答1:

When you want to serialize objects, you pass object as a first argument.

serializer = CommentSerializer(comment)
serializer.data
# {'email': u'leila@example.com', 'content': u'foo bar', 'created': datetime.datetime(2012, 8, 22, 16, 20, 9, 822774)}

But when you want to deserialize you pass the data with a data kwarg.

serializer = CommentSerializer(data=data)
serializer.is_valid()
# True
serializer.validated_data
# {'content': 'foo bar', 'email': 'leila@example.com', 'created': datetime.datetime(2012, 08, 22, 16, 20, 09, 822243)}

So in your case you want to deserialize your post data, therefor you have to do:

serializer = PatientNoteSerializer(data=request.data)