[Answered ]-NameError: name 'ObjectNotExist' is not defined

1👍

You use Model.DoesNotExist with Model the one for which we query that might not return anything, or ObjectDoesNotExist. The former is more specific and therefore often a better idea:

def cart(request, total=0, quantity=0, cart_item=None):
    try:
        cart = Cart.objects.get(cart_id=_cart_id(request))
        cart_items = CartItem.objects.filter(cart=cart, is_active=True)
        for cart_item in cart_items:
            total += cart_item.product.price * cart_item.quantity
            quantity += cart_item.quantity

    except Cart.DoesNotExist:
        total = quantity = cart_items = None

    context = {
        'total': total,
        'quantity': quantity,
        'cart_items': cart_items,
    }
    return render(request, 'store/cart.html', context)

Leave a comment