def add_to_cart(request, slug): user = None item_id = None if request.user.is_authenticated: user = request.user cart = request.session.get('cart') if cart is None: cart = [] item = Product.objects.get(slug=slug) flag = True for cart_obj in cart: item_id = cart_obj.get('item') if item_id == item.id: flag = False cart_obj['quentity'] = cart_obj['quentity'] + 1 if flag: cart_obj = {'item': item.id, 'quentity': 1} cart.append(cart_obj) if user is not None: product_obj = Product.objects.get(slug=slug) existing = Cart.objects.filter(user=user, product=product_obj) if len(existing) > 0: obj = existing[0] obj.quentity = obj.quentity + 1 obj.save() else: c = Cart() c.user = user c.product = Product.objects.get(slug=slug) c.quentity = 1 c.save() request.session['cart'] = cart return_url = request.GET.get('return_url') return redirect(return_url)
def login(request): if request.method == "GET": form = UserLoginForm() return render(request, template_name='store/login.html', context={'form': form}) else: form = UserLoginForm(data=request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) if user: userlogin(request, user) session_cart = request.session.get('cart') if session_cart is None: session_cart = [] else: for c in session_cart: item = c.get('item') quentity = c.get('quentity') cart_obj = Cart() cart_obj.product = Product.objects.get(id=item) cart_obj.quentity = quentity cart_obj.user = user cart_obj.save() cart = Cart.objects.filter(user=user) session_cart = [] for c in cart: obj = {'item': c.product.id, 'quentity': c.quentity} session_cart.append(obj) request.session['cart'] = session_cart return redirect("home") else: return render(request, template_name='store/login.html', context={'form': form})