简体   繁体   中英

Django: AttributeError at /update_item/ 'WSGIRequest' object has no attribute 'data'

The following error is given to me when i access my localhost:8000/update_item/: "AttributeError at /update_item/ 'WSGIRequest' object has no attribute 'data'"

views.py

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

    customer = request.user.customer
    product = Product.objects.get(id=productId)
    order, created = Order.objects.get_or_create(customer=customer, complete=False)
    orderItem, created = OrderItem.objects.get_or_create(order = order, product = product)

carrito.js:

function updateUserOrder(productId, action){
    console.log('Usuario logeado y enviando 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)
        location.reload()
    })

}

The error is in the following line:

data = json.loads(request.data)

if i change that line to the following:

data = json.loads(request.body)

It gives me another error: "JSONDecodeError at /update_item/ Expecting value: line 1 column 1 (char 0)"

Try this instead of request.data

def updateItem(request):

     if request.method =='POST':
            productId = request.POST['productId'] 
            action = request.POST['action ']

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