简体   繁体   中英

Importing Data from a JSON to django AttributeError: 'WSGIRequest' object has no attribute 'data'

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM