DRF:数据未通过补丁方法传递给kwargs

时间:2019-09-05 06:45:06

标签: django django-rest-framework

我正在为我的应用创建更新评论视图。这是我的代码:

serializer.py

class CommentSerializer(serializers.ModelSerializer):

    class Meta:
        model = FitnessRecord
        fields = ('comment', 'id')

views.py

class AddCommentView(APIView):
    permission_classes = [IsAuthenticated]

    def patch(self, request, *args, **kwargs):
        print(kwargs) # this is printing {}
        instance = get_object_or_404(FitnessRecord, pk=kwargs.get('id')) # error line
        print(22222) # not printing
        serializer = CommentSerializer(instance, data=request.data, partial=True)

        if serializer.is_valid():

            serializer.save()

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

我正在使用邮递员发送数据。这是错误:

{
    "detail": "Not found."
}

这可能是因为kwargs空白。

我正在传递这些数据。

{
    "comment": "gotham#bw9",
    "id": 14
}

如果需要,这是DRF设置。

REST_FRAMEWORK = {
    # Use Django's standard `django.contrib.auth` permissions,
    # or allow read-only access for unauthenticated users.
    'DATE_INPUT_FORMATS': ['%d-%m-%Y'],
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
    ),
    'TEST_REQUEST_DEFAULT_FORMAT': 'json'
}

2 个答案:

答案 0 :(得分:1)

您应该在网址中传递kwarg id。参见下面的示例

URL:

http://localhost:8000/comment/14/

请求方法:PATCH

数据:

{
    "comment": "gotham#bw9",
}

答案 1 :(得分:1)

您可以使用request.data获得发送的有效载荷;

def patch(self, request, *args, **kwargs):
    print(request.data) # this will print {"comment": "gotham#bw9", "id": 14}
    ...