I have had a hunt around but can't seem to find an answer that works. I am following Dennis Ivy's Django tutorial for an e-commerce website but I have run in to an issue where I am trying to add an item to my cart but nothing happens, checking the console I am getting these two errors:
POST http://127.0.0.1:8000/update_item/ 500 (Internal Server Error)
updateUserOrder @ cart.js:26 (The fetch line)
(anonymous) @ cart.js:15 (when the function is called)
127.0.0.1/:1 Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
omise.then (async)
updateUserOrder @ cart.js:39 (the second .then)
(anonymous) @ cart.js:15 (when the function is called)
Here is my JavaScript cart.js updateUserOrder function:
function updateUserOrder(productId, action) {
console.log('User is logged in, sending 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) => {
location.reload()
});
}
Here is my view updateItem:
def updateItem(request):
data = json.loads(request.body)
productId = data['productId']
action = data['action']
print('Action:', action)
print('Product:', 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)
if action == 'add':
orderItem.quantity = (orderItem.quantity + 1)
elif action == 'remove':
orderItem.quantity = (orderItem.quantity - 1)
orderItem.save()
if orderItem.quantity <= 0:
orderItem.delete()
return JsonResponse('Item was added', safe=False)
Here is my URL including import:
from checkout.views import updateItem
path('update_item/', updateItem, name="update_item"),
Thanks in advance!