Django rest Framework在另一个基于类的视图中将json发送到api端点

时间:2017-11-16 06:21:24

标签: django django-rest-framework

我想从CBV中发布到端点并检索响应(以便访问所创建资源的id)。我查看了How to programmatically call a Django Rest Framework view within another view?,但无法找到如何通过请求对象发送字段值。 request.data是不可变的,并且传递kwargs似乎没有做任何事情:

from app.views import OtherViewSet

class NewViews(APIView):
   def post(self, request, *args, **kwargs):
       # kwargs value here is {'field1':1, 'field2':2...}
       view_func = OtherViewSet({'post':'create'})
       response = view_func(self.request, *args, **kwargs).data

虽然kwargs包含字段值(通过几个名为groups的url设置),但响应总是如下:

{'field1': ['This field is required'], 'field2':['This field is required...

我做错了什么?谢谢大家:))

编辑: 一旦我获得了创建资源的ID,我想检索由特定(自定义)格式呈现的资源(我不想返回上面的响应对象)。

1 个答案:

答案 0 :(得分:0)

<强> views.py

from app.views import OtherViewSet

class NewViews(APIView):
    def post(self, request, *args, **kwargs):
        view = OtherViewSet.as_view({'post':'create'})
        response = view(request, *args, **kwargs)
        return response