JsonResponse by default expect to return a Json Dict. Using: safe=False you override this behavior telling that it’s OK to return a non dict object.
Your problem is that in this line:
return response.json()
Your JS code wait as well for a dict.
So you have to pass a JsonDict in the response and JS will be able to parse it
I have a simple add and remove button for a cart, but whenever i click on the button, i get an error in the console, please bear in mind, i a newbie:
cart.js:25 POST http://127.0.0.1:8000/update_item/ 404 (Not Found)
updateUserOrder @ cart.js:25
(anonymous) @ cart.js:14
127.0.0.1/:1 Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
And this is the error i get in my terminal:
Not Found: /update_item/
I strongly feel this is the problem, as the fetch is not recognizing update_item in views.py
This is the code in cart.js:
function updateOrder (ticketId, 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({'ticketId': ticketId, 'action':action})
})
.then((response) =>{
return response.json()
})
.then((data) =>{
console.log('data:', data)
location.reload()
})
}
This is my views.py code:
def updateItem(request):
data = json.loads(request.body)
ticketId = data['ticketId']
action = data['action']
print('Action:', action)
print('ticketId:', ticketId)
customer = request.user.customer
ticket = Ticket.objects.get(id=ticketId)
order, created = Order.objects.get_or_create(customer=customer, complete=False)
orderItem, created = OrderItem.objects.get_or_create(order=order, ticket=ticket)
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)
This is it path(‘checkout/’, views.checkout, name=”checkout”), path(‘update_item/’, views.updateItem, name=”update_item”),
If you are not going to use the Json properly in the response but to console.log a success message, probably the straigth forward way: not return a Jsonresponse from views and use a string in JS to return that messagge.
I have that so that i know it worked. But it not working
As I said response.json wait for a dictionnary not a string. like {‘status’:’ok’} this is a json dictionnary