Django:/update_item/ 'WSGIRequest' 对象的 AttributeError 没有属性 'data'

问题描述

当我访问我的 localhost:8000/update_item/ 时出现以下错误:“AttributeError at /update_item/ 'WSGIRequest' 对象没有属性 'data'”

views.py

def updateItem(request):
    data = json.loads(request.data)
    productId = data['productId']
    action = data['action']
    print('Action:',action)
    print('productId:',productId)

    customer = request.user.customer
    product = Product.objects.get(id=productId)
    order,created = Order.objects.get_or_create(customer=customer,complete=False)
    orderItem,created = OrderItem.objects.get_or_create(order = order,product = product)

carrito.js:

function updateUserOrder(productId,action){
    console.log('Usuario logeado y enviando data...')

    var url = '/update_item/'

    fetch (url,{
        method: 'POST',headers:{
            'Content-Type':'application/json','X-CSRFToken': csrftoken,},body:JSON.stringify({'productId' :productId,'action' :action})
    })

    .then((response) =>{
        return response.json()
    })

    .then((data) =>{
        console.log('data:',data)
        location.reload()
    })

}

错误在以下行:

data = json.loads(request.data)

如果我将该行更改为以下内容:

data = json.loads(request.body)

它给了我另一个错误:“JSONDecodeError at /update_item/ 期望值:第 1 行第 1 列(字符 0)"

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)