首页 > 解决方案 > 将数据从 JSON 导入 django AttributeError: 'WSGIRequest' 对象没有属性 'data'

问题描述

我正在尝试从教程系列- Django Ecommerce Website |制作一个电子商务网站 添加到购物车功能 | django framwork 中的第 3 部分。

我的views.py是:

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

    print('productId: ', productId)
    print('action: ', action)
    return JsonResponse('Item was added', safe=False)

我的js文件是:

var updateBtns = document.getElementsByClassName('update-cart')
console.log('updateBtns length:', updateBtns.length);
for(var i=0; i<updateBtns.length; i++){
  updateBtns[i].addEventListener('click', function(){
    var productId = this.dataset.product
    var action = this.dataset.action
    console.log('product ID: ', productId, "Action: ", action)
    console.log('User: ', user)
    if (user == 'AnonymousUser'){
      console.log('user is not authnticated');
    }
    else{
      updateUserOrder(productId, action);
    }
  })
}
function updateUserOrder(productId, action){
  console.log('user is authenticatred, sending 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)
  })
}

这里我的问题是在views.py的updateItem函数中添加这些行之后,错误显示在控制台中-

data = json.loads(request.data)
AttributeError: 'WSGIRequest' object has no attribute 'data'

我怎么解决这个问题?其实我不太清楚rest API或json。

标签: javascriptdjangodjango-rest-framework

解决方案


做:

data = json.loads(request.body)

正如控制台中所建议的那样:'WSGIRequest' object has no attribute 'data'这是完全正确的。但是,它有一个名为body

具体来说,在您的 js 中,fetch您已将数据发送到request.body

    body: JSON.stringify({'productId': productId, 'action': action}) // Here

有关django_response_and_request的更多信息


推荐阅读