I am trying to make an E-commerce website from the tutorial series- Django Ecommerce Website | Add to Cart Functionality | Part 3 in django freamwork.
My views.py is:
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)
My js file is:
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)
})
}
Here my problem is after adding those line in updateItem function in views.py the error is shown in the console-
data = json.loads(request.data)
AttributeError: 'WSGIRequest' object has no attribute 'data'
How can I solve this problem? Actually I do not know about rest API or json clearly.