Issue with Quantity Increment in Django E-commerce Cart

20 Views Asked by At

Description:

I'm encountering an unexpected behavior in my Django e-commerce website where the quantity of items in the cart increments at an exponential rate instead of a linear one. Here's a breakdown of the problem and the relevant code snippets: Here's the complete github repository link: https://github.com/HamzaArif538/Bouncer

Problem Description:

When adding an item to the cart, the quantity appears to double with each click of the "add" button. For instance, if I add an item once, it shows a quantity of 3 instead of 1. Then, upon adding it again, the quantity jumps to 6 instead of 2, and so forth. Similarly, when decreasing the quantity using the "remove" button, it doesn't decrement linearly but exhibits similar exponential behavior.

Code Snippets:

cart.html: This snippet shows the HTML code responsible for displaying the quantity and buttons to add or remove items from the cart.

<div class="li-cartstyle cartbodyinformation-quantity">
<p class="quantity-input">{{ item.quantity }}</p>
<div class="cartquantity-buttons">
    <i data-product={{ item.product.id }} data-action="add" class="update-cart change-quantity fa-solid fa-angle-up"></i>
    <i data-product={{ item.product.id }} data-action="remove" class="update-cart change-quantity fa-solid fa-angle-down"></i>
</div>

cart.js: This JavaScript code handles the interactions with the cart, such as adding or removing items.

        // var user = '{{request.user}}'

    var updateBtns = document.getElementsByClassName('update-cart')

    var user = isAuthenticated ? 'AuthenticatedUser' : 'AnonymousUser';

    for(var i=0; i < updateBtns.length; i++){
        updateBtns[i].addEventListener('click', function(){
            var productId = this.dataset.product
            var action = this.dataset.action
            console.log('productId:', productId, '\naction: ', action)

            console.log('USER: ',user)

            if(user === 'AnonymousUser'){
                addCookieItem(productId, action)
            }
            else{
                updateUserOrder(productId, action)
            }
        })
    }

    function addCookieItem(productId, action){
        console.log('Not Logged in')

        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('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()
        })
    }

views.py: This Python code contains the backend logic for updating the cart items.

def updateItem(request):
data = json.loads(request.body)
productId = data['productId']
action = data['action']

print('Action:', action)
print('productId:', 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)

Additional Context:

The website is built using Django framework. The issue seems to persist regardless of whether the user is authenticated or not. Upon inspecting the network requests, I notice that the updateItem view in views.py is being called correctly, but the quantity manipulation there seems to result in unexpected behavior.

Desired Outcome:

I expect the quantity of items in the cart to increment or decrement by one unit upon clicking the respective buttons. I would appreciate any insights or suggestions on how to resolve this issue and ensure the quantity adjustments behave as expected.

Thank you in advance for your assistance! If further clarification or code snippets are needed, please let me know.

0

There are 0 best solutions below