예제 #1
0
def cart(request):
    try:
        cart_id = request.session['cart_id']
        cart = Cart.objects.get(id=cart_id)
        request.session['total'] = cart.items.count()
    except DoesNotExist:
        cart = Cart()
        cart.save()
        cart_id = cart.id
        request.session['cart_id'] = cart_id
        cart = Cart.objects.get(id=cart_id)

    template = 'cart.html'
    if request.method == 'POST':
        new_order = Order()
        new_order.user = request.user
        new_order.total = cart.cart_total
        new_order.save()
        for item in cart.items.all():
            cart.items.remove(item)
            cart.save()
        return render(request, template)

    new_cart_total = 0
    for item in cart.items.all():
        new_cart_total += item.item_total

    cart.cart_total = new_cart_total
    cart.save()
    context = {
        'cart': cart
    }
    return render(request, template, context)
예제 #2
0
def remove_from_cart_view(request):
    try:
        cart_id = request.session[
            'cart_id']  # Получение значения сессии при помощи ключа(то есть, 'cart_id').
        cart = Cart.objects.get(id=cart_id)
        request.session['total'] = cart.items.count()
    except:
        cart = Cart()
        cart.save()
        cart_id = cart.id
        request.session['cart_id'] = cart_id  # Передача значения в сессию
        cart = Cart.objects.get(id=cart_id)
    product_slug = request.GET.get('product_slug')
    product = Product.objects.get(slug=product_slug)
    cart.remove_from_cart(product.slug)
    new_cart_total = 0.00
    for item in cart.items.all():
        new_cart_total += float(item.item_total)
        cart.cart_total = new_cart_total
        cart.save()
    return JsonResponse({
        'cart_total': cart.items.count(),
        'cart_total_price': cart.cart_total
    })