我在后端有一个Django Rest API,用于存储问题和答案。我也有提问环节,它是一系列问题,必须在1个请求之内处理。
问题是,当我通过curl发送这些请求但通过jquery发送这些请求时,Django收到的是QueryDict而不是json,效果很好。
我的js:
$.post('http://127.0.0.1:8000/api/sessions/create/', {
questions: JSON.stringify(questions)
})
当我登录JSON.stringify(questions)时,我发现它看起来必须是:
[{“ description”:“ test5”,“ type”:“ YESNO”,“ to_close”:5,“ choices”:“”},{“ description”:“ test5”,“ type”:“ YESNO “,” to_close“:5,”选择“:”“}]
我什至可以复制并粘贴它以卷曲,它将起作用:
curl -X POST http://127.0.0.1:8000/api/sessions/create/ -H'Content-Type:application / json'--data'{“ questions”:[{“ description”:“ test4”,“ type”:“ YESNO”, “ to_close”:5,“ choices”:“”},{“ description”:“ test3”,“ type”:“ YESNO”,“ to_close”:5,“ choices”:“”}]}}'
但是当我通过JS进行操作时,Django会以这种方式接收它:
<QueryDict: {'questions': ['[{"description":"test5","type":"YESNO","to_close":5,"choices":""},{"description":"test7","type":"YESNO","to_close":5,"choices":""}]']}>
我的发布方法如下:
def post(self, request, **kwargs):
"""Create a session of questions"""
question_data = request.data.pop('questions')
session = QuestionSession.objects.create()
for question in question_data:
Question.objects.create(
description=question['description'],
question_type=question['type'],
answers_to_close=question['to_close'],
question_session=session)
serializer = QuestionSessionSerializer(data=request.data, many=True)
serializer.is_valid()
serializer.save()
return Response({
'status': 'SUCCESS',
'message': 'A new session has been created!'
})
怎么了?由于我可以通过curl轻松完成此操作,因此我认为问题出在jquery请求中。
答案 0 :(得分:0)
我遇到了完全相同的问题,对我有用的是在帖子中添加, content_type="application/json"
。