Django 更新 api

Django update api

我要通过 django 创建用户配置文件更新 api:

在网址中:

url(r'^/api/users/(?P<user_id>[0-9]+)$', UserView.as_view(), name='user_profile'),

而我的观点:

class UserView(APIView):
    def patch(self, request, user_id):
        # logging.info('user Id: %s' % user_id)
        logging.info('in patch...')
        user = User.objects.get(id=user_id)
        serializer = UserSerializer(user, data=request.data, partial=True)
        if serializer.is_valid():
            serializer.save()
            return Response(status=status.HTTP_200_OK)
        return Response(status=status.HTTP_400_BAD_REQUEST)

为什么根本没有调用 patch def?! (我得到 504 方法不允许)

我的要求是:

补丁 > http://localhost:8000/api/users/2

当我删除视图中的 user_id 参数时,它有效,但我需要在路径中获取用户 ID。

def patch(self, request, user_id):
    # logging.info('user Id: %s' % user_id)
    logging.info('in patch...')
    user = User.objects.get(id=2)
    serializer = UserSerializer(instance=user, data=request.data, partial=True)
    if serializer.is_valid():
        serializer.save()
        return Response(status=status.HTTP_200_OK)
    return Response(status=status.HTTP_400_BAD_REQUEST)

您必须提供实例 eq:serializer = UserSerializer(instance=user, data=request.data, partial=True)

试试这个。

class UserView(APIView):
    def patch(self, request, *args, **kwargs):
        # try to get user_id from kwargs.get('user_id', None)