Rap*_*ael 5 django django-rest-framework
我有以下观点:
class Authenticate(generics.CreateAPIView):
serializer_class = AuthSerializer
def create(self, request):
serializer = AuthSerializer(request.POST)
# Do work here
Run Code Online (Sandbox Code Playgroud)
如果数据作为表单传递,这很有效,但是,如果数据作为原始JSON传递,则序列化程序将实例化,并将其所有字段设置为None.文档确实提到应该有任何特定的处理原始JSON参数.
任何帮助,将不胜感激.
UPDATE
我有以下工作,以便在传递原始JSON时使Browsable API按预期工作,但我相信必须有更好的方法.
def parse_data(request):
# If this key exists, it means that a raw JSON was passed via the Browsable API
if '_content' in request.POST:
stream = StringIO(request.POST['_content'])
return JSONParser().parse(stream)
return request.POST
class Authenticate(generics.CreateAPIView):
serializer_class = AuthSerializer
def create(self, request):
serializer = AuthSerializer(parse_data(request))
# Do work here
Run Code Online (Sandbox Code Playgroud)
您以错误的方式访问请求数据 - request.POST仅处理从多部分数据解析.
请改用REST框架request.data.这将处理表单数据或json数据,或者您配置的任何其他解析器.
| 归档时间: |
|
| 查看次数: |
3255 次 |
| 最近记录: |