Reputation: 949
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.
Upvotes: 2
Views: 3573
Reputation: 11
As a modification to this answer by Biplove Lamichhane:
data = json.loads(request.body)
I needed instead to do:
data = json.loads(request.body.decode("utf-8"))
As I was getting bytes from UI.
Upvotes: 1
Reputation: 4095
Do:
data = json.loads(request.body)
As suggest in the console: 'WSGIRequest' object has no attribute 'data'
and that's completely true. But, it has attribute called body
Specifically, in your js fetch
you have sent data to request.body
:
body: JSON.stringify({'productId': productId, 'action': action}) // Here
For more about django_response_and_request
Upvotes: 3