【问题标题】:Django: AttributeError at /update_item/ 'WSGIRequest' object has no attribute 'data'Django:/update_item/'WSGIRequest'对象的AttributeError没有属性'data'
【发布时间】:2021-04-30 13:52:51
【问题描述】:

当我访问我的 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()
    })

}

错误在以下行:

data = json.loads(request.data)

如果我将该行更改为以下内容:

data = json.loads(request.body)

它给了我另一个错误:“JSONDecodeError at /update_item/ 期望值:第 1 行第 1 列 (char 0)"

【问题讨论】:

    标签: javascript python django jsonresponse


    【解决方案1】:

    试试这个而不是 request.data

    def updateItem(request):
    
         if request.method =='POST':
                productId = request.POST['productId'] 
                action = request.POST['action ']
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-10
      • 2021-07-04
      • 2021-03-08
      • 2016-02-02
      • 1970-01-01
      • 2022-01-21
      • 2018-09-06
      • 1970-01-01
      相关资源
      最近更新 更多