Попытка добавить вариант товара в корзину js Django
Попытка добавить вариант товара в корзину js Django Я просто не очень понимаю, как добавить его в корзину в js и получить его в моем utils.py код хорошо работает до того, как я добавил варианты в models.py. Я действительно разрываюсь, как заставить это работать. какая правильная идея добавить его fo функцию addCookieItem в cart.js и отобразить его в utils.py
models.py
cart.js
var updateBtns = document.getElementsByClassName('update-cart')
for (i = 0; i < updateBtns.length; i++) {
updateBtns[i].addEventListener('click', function(){
var productId = this.dataset.product
var variantId = this.dataset.variant
var action = this.dataset.action
console.log('productId:', productId, 'variantId:', variantId, 'Action:', action)
console.log('USER:', user)
if (user == 'AnonymousUser'){
addCookieItem(productId, action)
}else{
updateUserOrder(productId, variantId, action)
}
})
}
function addCookieItem(productId, action){
console.log('User is not authenticated')
if (action == 'add'){
if (cart[productId] == undefined){
cart[productId] = {'quantity':1}
}else{
cart[productId]['quantity'] += 1
}
}
if (action == 'remove'){
cart[productId]['quantity'] -= 1
if (cart[productId]['quantity'] <= 0){
console.log('Item should be deleted')
delete cart[productId];
}
}
console.log('CART:', cart)
document.cookie ='cart=' + JSON.stringify(cart) + ";domain=;path=/"
location.reload()
}
utils.py
def cookieCart(request):
try:
cart = json.loads(request.COOKIES['cart'])
except:
cart = {}
print('CART:', cart)
items = []
order = {'get_cart_total':0, 'get_cart_items':0, 'shipping':False}
cartItems = order['get_cart_items']
for i in cart:
print('CART:', cart[i])
try:
cartItems += cart[i]['quantity']
product = Product.objects.get(id=i)
total = (product.price * cart[i]['quantity'])
order['get_cart_total'] += total
order['get_cart_items'] += cart[i]['quantity']
item = {
'id':product.id,
'product':{'id':product.id,'title':product.title,'price':product.price,
'imageURL':product.imageURL,'description':product.description,'category':product.category,'slug':product.slug,'variant':product.variant},
'variant':{'id':product.id,'title':product.name,
'product':product.id, 'color':product.name,'size':product.name, 'price':product.price,
'imageURL':product.imageURL},
'quantity':cart[i]['quantity'],'get_total':total,
}
items.append(item)
except:
pass
return {'cartItems':cartItems ,'order':order, 'items':items}