def add_cart_to_database(user, size, tshirt): size = SizeVarient.objects.get(size=size, tshirt=tshirt) existing = Cart.objects.filter(user=user, sizevarient=size) if len(existing) > 0: obj = existing[0] obj.quantity = obj.quantity + 1 obj.save() else: c = Cart() c.user = user c.sizevarient = size c.quantity = 1 c.save()
def post(self,request): form = CustomerAuthform(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: loginuser(request, user) session_cart = request.session.get('cart') if session_cart is None: session_cart = [] else: for c in session_cart: size = c.get('size') tshirt_id = c.get('tshirt') quantity = c.get('quantity') cart_obj = Cart() cart_obj.sizevarient = SizeVarient.objects.get(size=size, tshirt=tshirt_id) cart_obj.quantity = quantity cart_obj.user = user cart_obj.save() cart = Cart.objects.filter(user=user) session_cart = [] for c in cart: obj = { 'size': c.sizevarient.size, 'tshirt': c.sizevarient.tshirt.id, 'quantity': c.quantity, } session_cart.append(obj) request.session['cart'] = session_cart next_page = request.session.get('next_page') if next_page is None: next_page = 'homepage' return redirect(next_page) else: return render(request, template_name='store/login.html', context={'form': form})