Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
731 views
in Technique[技术] by (71.8m points)

javascript - 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)"

question from:https://stackoverflow.com/questions/65907130/django-attributeerror-at-update-item-wsgirequest-object-has-no-attribute-d

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try this instead of request.data

def updateItem(request):

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...