我正在为我的应用创建更新评论视图。这是我的代码:
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'
}
答案 0 :(得分:1)
您应该在网址中传递kwarg id
。参见下面的示例
http://localhost:8000/comment/14/
{
"comment": "gotham#bw9",
}
答案 1 :(得分:1)
您可以使用request.data
获得发送的有效载荷;
def patch(self, request, *args, **kwargs):
print(request.data) # this will print {"comment": "gotham#bw9", "id": 14}
...