def cart(request): """It showes customer's cart and allows to change products numbers. """ cart = Cart(request) products = cart.get() products_ids = {p.id: p for p in products} OrderFormSet = formset_factory(OrderForm, extra=0) if request.method == 'POST': formset = OrderFormSet(request.POST) if formset.is_valid() and formset.has_changed(): for cd in formset.cleaned_data: product = get_object_or_404(Product, pk=cd['product']) cart.add_or_update(product, cd['count']) else: data = [{'product': p.id, 'count': c} for p, c in products.items()] formset = OrderFormSet(initial=data) for form in formset: form.product_info = products_ids[int(form.hidden_fields()[0].value())] context = { 'products': products, 'formset': formset, 'cart_count': cart.count(), 'total': cart.total(), } return cart.set(render(request, 'sales/cart.html', context))
def add(request, id): """It adds the product to the Cart""" product = get_object_or_404(Product, pk=id) cart = Cart(request) cart.add_or_update(product, 1) context = { 'product': product, 'in_cart': cart.has(product), 'cart_count': cart.count(), } return cart.set(render(request, 'sales/show.html', context))
def delete(request, id): """It removes the product from the Cart""" product = get_object_or_404(Product, pk=id) cart = Cart(request) cart.delete(product) return cart.set(redirect(reverse('cart')))