我正在尝试在项目中构建购物车系统。我为此使用django和javascript。但是当我单击“添加到购物车”时,产品并未添加到购物车
这是我的views.py
def updateCart(request):
data = json.loads(request.body)
productId = data['productId']
action = data['action']
print('productId:',productId)
print('Action:',action)
customer = request.user.customer_name
product = ProductModel.objects.get(product_id=productId)
order, created = OrderModel.objects.get_or_create(customer=customer, complete=False)
orderItem, created = orderItem.objects.get_or_create(order=order, product=product)
if action == 'add':
orderItem.quantity = (orderItem.quantity + 1)
elif action == 'remove':
orderItem.quantity = (orderItem.quantity - 1)
orderItem.save()
if oderItem.quantity <= 0:
orderItem.delete()
return JsonResponse('Item has been added to cart', safe=False)
这是我的cart.js
var updateBtn = document.getElementsByClassName('update-cart')
for(var i = 0; i < updateBtn.length; i++){
updateBtn[i].addEventListener('click', function(){
var productId = this.dataset.product
var action = this.dataset.action
console.log('productId:',productId, 'action:',action)
console.log('USER:',user)
if(user === 'AnonymouseUser'){
console.log('Please Login to Order!')
}
else {
updateUserOrder(productId, action)
}
})
}
function updateUserOrder(productId, action){
console.log('Product added to cart!')
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()
})
}
我已经添加了csrf令牌,但仍然遇到此错误。我修改了很多次代码,但找不到主要问题。我不知道该怎么办,我被困在这里:(
这是我遇到的错误:
POST http://127.0.0.1:8000/update_item/ 500 (Internal Server Error)
updateUserOrder @ cart.js:24
(anonymous) @ cart.js:14
(index):1 Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0