【问题标题】:Django receiving QueryDict instead of JSON (from jQuery post)Django 接收 QueryDict 而不是 JSON(来自 jQuery 帖子)
【发布时间】:2019-06-18 03:13:15
【问题描述】:

我在后端有一个存储问题和答案的 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,"choices":""}]

我什至可以将其复制并粘贴到 curl,它会起作用:

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":""}]']}>

我的 post 方法如下所示:

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 请求中。

【问题讨论】:

  • 你是怎么输出的?是什么让你觉得有问题?你的观点真的有效吗?您是否像使用 curl 一样从 JS 设置内容类型?
  • @DanielRoseman 我正在输出 print(request.data) 。当我通过 curl 发出请求并且它得到 JSON 时,我的视图确实有效
  • 您没有回答主要问题。 从 JS 发送数据时会发生什么?您是否设置了内容类型?
  • @DanielRoseman 当我将它从 $.post 重写为 $.ajax 时它开始工作了

标签: python jquery json django


【解决方案1】:

我遇到了同样的问题,对我有用的是在我的帖子中添加, content_type="application/json"

【讨论】:

  • @Yunnosch 抱歉!并没有试图居高临下。编辑了我原来的帖子
  • 澄清一下。我只是说任何问题都可能被误解为不是答案。否则,我只会在您的帖子中阅读礼貌的内容。在我看来,它需要被强制和故意误读才能最终变得不礼貌。 (但是是的,人们有时会这样做......)
猜你喜欢
  • 2023-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-10
  • 1970-01-01
  • 1970-01-01
  • 2012-06-18
  • 2017-05-05
相关资源
最近更新 更多