Creating an e-commerce website project to try and learn Django and more about Javascript, so I have been going over a tutorial for the past week. In the tutorial, there is a guest user cart feature. It works by storing user and product data into the cookies. Though, I am having trouble getting it to add multiple of the same item. If I were to login as a user the website works fine. The remove feature works fine for deleting an item out of the cart as guest. In the JavaScript console, the items in the cart get deleted, but the cookies retain the same information before the website reloads. Don’t know the cause for this issue. I would really like this feature to work out.
JavaScript Console Log
cart.js
var updateBtns = document.getElementsByClassName('update-cart')
for(var i = 0; i < updateBtns.length; i++) {
updateBtns[i].addEventListener('click', function() {
//sets variable to add to the dictionary.
var productId = this.dataset.product
var action = this.dataset.action
console.log('productId:', productId, 'action:', action)
//checks to see if the user is logged in.
console.log('USER:', user)
if (user === 'AnonymousUser') {
addCookieItem(productId, action)
} else {
updateUserOrder(productId, action)
}
})
}
function addCookieItem(productId, action) {
console.log('Not logged in.')
//add quantity to the cart by 1
if (action == 'add') {
if(cart[productId] == undefined) {
cart[productId] = {'quantity':1}
} else {
cart[productId]['quantity'] += 1
}
}
//removes quantity to the cart by 1
if (action == 'remove') {
cart[productId]['quantity'] -= 1
if(cart[productId]['quantity'] <= 0){
console.log('Remove Item')
delete cart[productId]
}
}
console.log('Cart:', cart)
//
document.cookie = 'cart=' + JSON.stringify(cart) + ";domain=;path=/"
location.reload()
}
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) =>{
console.log('data:', data)
location.reload()
})
}
main.html
var user = '{{request.user}}';
function getToken(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i=0; i<cookies.length; i++) {
var cookie = cookies[i].trim();
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var csrftoken = getToken('csrftoken');
function getCookie(name) {
var cookieArr = document.cookie.split(";")
for(var i=0;i<cookieArr.length; i++) {
var cookiePair = cookieArr[i].split("=");
if(name == cookiePair[0].trim()) {
return decodeURIComponent(cookiePair[1]);
}
}
return null;
}
var cart = JSON.parse(getCookie('cart'))
if (cart == undefined) {
cart = {}
console.log('Cart was created', cart)
document.cookie = 'cart=' + JSON.stringify(cart) + ";domain=;path=/"
}
console.log("Cart:", cart);
utils.py
import json
from .models import *
def cookieCart(request):
if request.user.is_authenticated:
customer = request.user.customer
order, created = Order.objects.get_or_create(customer=customer, complete=False)
items = order.orderitem_set.all()
cartItems = order.get_cart_items
else:
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:
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 = {
'product': {
'id':product.id,
'name':product.name,
'price':product.price,
'imageURL':product.imageURL
},
'quantity':cart[i]['quantity'],
'get_total':total,
}
items.append(item)
if product.digital == False:
order['shipping'] = True
except:
pass
return {'cartItems':cartItems, 'order':order, 'items':items}
def cartData(request):
if request.user.is_authenticated:
customer = request.user.customer
order, created = Order.objects.get_or_create(customer=customer, complete=False)
items = order.orderitem_set.all()
cartItems = order.get_cart_items
else:
cookieData = cookieCart(request)
cartItems = cookieData['cartItems']
order = cookieData['order']
items = cookieData['items']
return {'cartItems':cartItems, 'order':order, 'items':items}
def guestOrder(request, data):
print('User is not logged in..')
print('COOKIES:', request.COOKIES)
name = data['form']['name']
email = data['form']['email']
cookieData = cookieCart(request)
items = cookieData['items']
customer, created = Customer.objects.get_or_create(
email=email,
)
customer.name = name
customer.save()
order = Order.objects.create(
customer=customer,
complete=False,
)
for item in items:
product = Product.objects.get(id=item['product']['id'])
orderItem = OrderItem.objects.create(
product=product,
order=order,
quantity=item['quantity'],
)
return customer, order
views def cart(request):
if request.user.is_authenticated:
customer = request.user.customer
order, created = Order.objects.get_or_create(customer=customer, complete=False)
items = order.orderitem_set.all()
cartItems = order.get_cart_items
else:
cookieData = cookieCart(request)
cartItems = cookieData['cartItems']
order = cookieData['order']
items = cookieData['items']
context = {'items':items, 'order':order, 'cartItems':cartItems}
return render(request, 'store/cart.html', context)
Help would be greatly appreciated! This is my first stack overflow post, so if you are reading this and know what I am doing wrong please let me know!




