【问题标题】:Bad Request when accessing request.data访问 request.data 时出现错误请求
【发布时间】:2019-09-22 00:28:01
【问题描述】:

我想通过 Ajax 将数据发送到我的 Django 服务器。但是当我想读取这些数据时,我得到了一个错误的请求错误。我不知道为什么,其他方法如 request.method 或 request.stream 效果很好。

这是 Ajax 调用:

jQuery.ajax({
        type: 'post',
        url: 'http://127.0.0.1:8000/termin/get-journey-time/',
        contentType: 'application/json; charset=utf-8',
        data: {
            'method': 'get_journey_time',
            'mandant_id': 1,
            'customer_address': customer_address,
            'staff_group': staff_group_id
        },
        success: function (resultData) {
            console.log(resultData)
        });

这是我对这个帖子请求的看法:

class get_journey_time(generics.ListAPIView):
    """
    Handle Ajax Post to calculate the journey time to customer for the selected staff group
    """
    permission_classes = (AllowAny,)

    def post(self, request, *args, **kwargs):
        body = request.data
        return Response(body)

我收到错误代码 400 错误请求。你知道为什么吗?

def post(self, request, *args, **kwargs):
        body = request.method
        return Response(body)

def post(self, request, *args, **kwargs):
        body = request.stream
        return Response(body)

好好工作

【问题讨论】:

  • 你试过from django.http import JsonResponse吗?
  • 日本但这里一样
  • post() 中放一个print("foo") 函数来检查请求是否命中
  • print('foo')works,以及 request.method 或 request.stream
  • 可以添加错误回溯吗?

标签: javascript python ajax django django-rest-framework


【解决方案1】:

您收到 HTTP 400 是因为您的代码引发了异常。由于其他方法有效,它必须是body = request.data 部分。看完docs 我认为解析您发布的数据一定有问题。比如,这里不需要序列化器吗?

【讨论】:

    【解决方案2】:

    我发现了我的错误。

    在阅读了django rest框架文档后,我发现我在post方法中调用了错误的参数。

    def post(self, request, format=None): 而不是 def post(self, request, *args, **kwargs) 为我工作。 谢谢大家,最好的!

    【讨论】:

      猜你喜欢
      • 2015-06-13
      • 1970-01-01
      • 1970-01-01
      • 2023-03-12
      • 1970-01-01
      • 2020-10-14
      • 2014-12-15
      • 2017-12-30
      • 1970-01-01
      相关资源
      最近更新 更多