【问题标题】:QueryDict coming through in django instead of JSON when AJAXingAJAXing 时 QueryDict 在 django 中而不是 JSON 中通过
【发布时间】:2023-03-03 07:55:22
【问题描述】:

我在一个 javascript 页面上有 8 个 ajax 调用。

7 都是这样,在 Django 中去 python 中的同一个视图进行解析和东西:

$.ajax({
    url: '/apiForStuff",
    type: 'POST',
    cache: false,
    data: JSON.stringify({'boxStuff': stuff}),
    contentType: "application/json",
    dataType: 'json',
    success: function(data) {
        table.reload()
    },
    error: function(err) {
        console.log('err', err)
    }
});

1 是这样的:

$.ajax({
        url: '/otherAPIStuff",
        data: formData,
        type: 'POST',
        cache: false,
        contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
        processData: false,
        dataType: 'json',
        success: function(data) {
            table.reload()
            
        },
        'error': function(err) {
            console.log('err', err)
        }
    });

第一个调用的视图(和六个类似的):

@method_decorator(login_required, name='dispatch')
class StuffUpdater(LayerDetailMixin, ApplicationDomainMixin, generic.TemplateView):
    
    def post(self, request, *args, **kwargs):
        print(request.POST)
        post_request = json.loads(request.POST)

print 语句打印一个 QueryDict,然后 json.loads 继续失败:

TypeError: the JSON object must be str, bytes or bytearray, not QueryDict

【问题讨论】:

标签: python django ajax


【解决方案1】:

您要做的是使用 json.loadsrequest.POST(一个 QueryDict 对象,已由 Django 使用请求正文转换)转换为字典(只需要 strbytesbytearray 个实例)。

如果您需要访问请求中发布的原始数据或非表单数据,请改为通过request.body 属性访问。


这是Django Documentation的摘录:

request.POST/request.GET

HttpRequest 对象中,GETPOST 属性是 django.http.QueryDict 的实例,类字典类 定制以处理同一个键的多个值。这是 必要的,因为某些 HTML 表单元素,特别是 为同一个键传递多个值。

request.POSTrequest.GET 的 QueryDict 将是不可变的 在正常的请求/响应周期中访问时。获得一个可变的 您需要使用request.POST.copy()request.GET.copy() 的版本。

【讨论】:

    【解决方案2】:

    你不能使用json.loads,根据定义,这个方法应该用于 使用此转换表将 s(包含 JSON 文档的 str、bytes 或 bytearray 实例)反序列化为 Python 对象。

    根据定义,在HttpRequest (django) 对象中,GET 和 POST 属性是django.http.QueryDict 的实例,django.http.QueryDict 是一个类字典类,为处理同一个键的多个值而定制。

    因此,您可以像这样将QueryDict 转换为dict

    myDict = dict(queryDict.iterlists())
    

    【讨论】:

      猜你喜欢
      • 2019-06-18
      • 2014-09-27
      • 2011-02-04
      • 2018-08-23
      • 2019-02-23
      • 2020-03-07
      • 1970-01-01
      • 1970-01-01
      • 2014-02-26
      相关资源
      最近更新 更多