Django:AttributeError at /course/u/update-item/'WSGIRequest' object has no attribute 'data' using django

Django: AttributeError at /course/u/update-item/ 'WSGIRequest' object has no attribute 'data' using django

当我尝试访问 localhost:8000/course/u/update-item/ 时出现此错误:“AttributeError at /update_item/ 'WSGIRequest' object没有属性 'data'"

注意:当我将 request.data 更改为 request.body 时,我收到另一条错误消息,上面写着 JSONDecodeError at /course/u/update-item/ Expecting value: line 1 column 1 (char 0)

views.py

def update_item(request):
    data = json.loads(request.data)
    productId = data['productId']
    action = data['action']
    print("Action:", action)
    print("ProductId:", productId)
    return JsonResponse("Item was added", safe=False)

cart.js

function updateUserOrder(productId, action){
    console.log('User is authenticated, sending data...')

        var url = '/u/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) => {
            location.reload()
        });
}

urls.py

    path('u/update-item/', views.update_item, name="update-item"),

WSGIRequest 对象没有属性 'data',在您的情况下,您必须将数据属性更改为 POST

data 属性用于 django rest 框架。查看 this