javascript - 将数据从 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。
解决方案
做:
data = json.loads(request.body)
正如控制台中所建议的那样:'WSGIRequest' object has no attribute 'data'
这是完全正确的。但是,它有一个名为body
具体来说,在您的 js 中,fetch
您已将数据发送到request.body
:
body: JSON.stringify({'productId': productId, 'action': action}) // Here
推荐阅读
- javascript - 制作适合多人游戏的画布视口
- javascript - 获取 TypeError:jquery__WEBPACK_IMPORTED_MODULE_1___default(...)(...).fancybox 不是函数
- html - Bootstrap 列 - 3 列,中心列最大化尺寸
- jquery - jquery 插件 .append .each 和一个 uniqe id
- python - Plotly Graph Python上的Y轴值乱序
- mongodb - 使用 atlas mongodb 服务器的 MERN 项目中的错误
- c - LD_PRELOAD 是否可能只影响主可执行文件?
- python - Python Selenium driver.get() 不会打开 url
- python-3.x - 将 xpath 用于 WebElement 数组
- python - Python:即使证书存在,SSL 也无法获取本地颁发者证书