【问题标题】:Django json loads fails because of empty query dict in request Object由于请求对象中的空查询字典,Django json 加载失败
【发布时间】:2019-09-10 03:26:01
【问题描述】:

我已将 ajax 调用发布到 /cart/total,当我运行 json 加载时,我使用 post 转储存储在本地存储中的 JSON 字符串,它向我显示错误。

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

在解析之前我的 JSON 字符串看起来像一个空字段,我在 Django 中不知道

<QueryDict: {'{"32":1,"33":1,"34":2}': ['']}>
<script>


    function addtocart(mitem, mprice) {

        if(localStorage.getItem('cart')==null){
            // var mobj = {}
            // var countQ ={}
            var price = String(mprice)
            var mobj = { [String(mitem)]: 1 }
            var countQ = {'Quantity':1}
            var storeobj = JSON.stringify(mobj)
            var storeCountq = JSON.stringify(countQ)
            localStorage.setItem('cart', storeobj)
            localStorage.setItem('quantity',storeCountq)
            console.log(localStorage.getItem('cart'))
        }else{
            var data = localStorage.getItem('cart')
            var quant = localStorage.getItem('quantity')
            var obj = JSON.parse(data)
            var parsequant = JSON.parse(quant)
            if(obj.hasOwnProperty(String(mitem))){
                obj['%s',mitem]++
                parsequant['Quantity']++
                var storeobj = JSON.stringify(obj)
                console.log(localStorage.getItem('cart'))
                var storeCountq = JSON.stringify(parsequant)
                localStorage.setItem('cart', storeobj)
                localStorage.setItem('quantity', storeCountq)
            }
            else{
                obj[String(mitem)] = 1
                parsequant['Quantity']++
                var storeobj = JSON.stringify(obj)
                console.log(localStorage.getItem('cart'))
                var storeCountq = JSON.stringify(parsequant)
                localStorage.setItem('cart', storeobj)
                localStorage.setItem('quantity', storeCountq)
            }
        }
        }

    function ajaxcall(){
            $.ajax(
                        {
                            type: "POST",
                            url: "/cart/total",
                            data: localStorage.getItem('cart'),
                            success: function () {
                                console.log("sent tdata")
                            }
                        })
                }

        ajaxcall()
    </script>
 <p style="position: absolute; bottom: 0px"><button class="button" style="width: 200px" onclick="addtocart( '{{M.Menu_Item_Id}}', '{{M.Menu_ItemPrice}}' )" >Add to cart</button>

查看功能

@csrf_exempt
def cartpricecalculator(request):
    if request.method == 'POST':
        data = json.loads(request.POST)
        print(request.POST)

    return HttpResponse('200 Okay')

我不确定我做错了什么,感谢任何帮助。

【问题讨论】:

  • 唯一我发现通过而没有破损的是json对象直接,然后将查询dict转换为dict

标签: ajax django local-storage


【解决方案1】:

request.POST 用于表单数据。你需要;

data = json.loads(request.body)

【讨论】:

  • 这是一个绝妙的主意@Daniel,从不知道你可以得到身体
【解决方案2】:

试试:

在 JS 中,传递一个 dict 而不是一个字符串。根据 ajax 的文档,数据必须是具有键和值的对象,或者是具有键和值的对象的字符串化。

参考:https://api.jquery.com/jQuery.ajax/

function ajaxcall(){
            $.ajax(
                        {
                            type: "POST",
                            url: "/cart/total",
                            data: {'cart': localStorage.getItem('cart')},
                            success: function () {
                                console.log("sent tdata")
                            }
                        })
                }

在python中

@csrf_exempt
def cartpricecalculator(request):
    if request.method == 'POST':
        cart_data = json.loads(request.POST.get('cart', '{}'))
        print(request.POST)
        print(request.POST.get('cart'))

    return HttpResponse('200 Okay')

【讨论】:

  • 很好,这个方法有效。现在我知道如何根据 API 标准来做。谢谢@sun_jara。
  • 很高兴我能帮上忙。
  • 如果您不介意,请接受该解决方案。谢谢@HarshNagarkar
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-12
  • 2013-01-13
  • 1970-01-01
相关资源
最近更新 更多