def add_to_cart(request, id): product = get_object_or_404(Product, id=id) cart = Cart(request) cart_form = CartForm(request.POST) if cart_form.is_valid(): data = cart_form.cleaned_data cart.add(product=product, quantity=data['quantity']) return redirect(product.get_absolute_url())
def post(self, request): form = CartForm(request.POST) if form.is_valid(): # instance = form.save(commit=False) # instance.user = '******' # instance.save() form.save() return HttpResponseRedirect(reverse_lazy('list-carts')) return render(request, 'cart/create_new_cart.html', {'form': form})
def add_to_cart(request): cart = Cart(request) form = CartForm(request.POST) if form.is_valid(): product_id = form.cleaned_data['product_id'] quantity = form.cleaned_data['quantity'] product = get_object_or_404(Product, id=product_id, availibility=True) cart.add(product_id, product.price, quantity) messages.success(request, f'{product.name} added to cart.') return redirect('cart:cart_details')
def cart_add(request, product_id): cart = Cart(request) product = get_object_or_404(Product, id=product_id) form = CartForm(request.POST) if form.is_valid(): cd = form.cleaned_data cart.add(product=product, quantity=cd['quantity'], update_quantity=cd['update']) return redirect('cart:cart_detail')
def add_to_cart(request, id): product_id = id if request.POST: username = request.user.id if username is not None: form = CartForm(request.POST) if form.is_valid(): cart = form.save(commit=False) cart.owner = User.objects.get(id=request.user.id) cart.product = Product.objects.get(id=id) form.save() return redirect('/cart') return redirect('/product/%s/' % product_id)
def prodet(request, slug): pro = Product.objects.get(slug=slug) if request.method == 'POST': if CartItem.objects.filter(product=pro, user_id=request.user.id): c = CartItem.objects.get(product=pro, user_id=request.user.id) d = pro.price * int(request.POST['quantity']) c.total_price += d c.quantity += int(request.POST['quantity']) c.save() # return HttpResponseRedirect(request.META.get('HTTP_REFERER')) return HttpResponseRedirect('/home/') else: d = pro.price * int(request.POST['quantity']) c = CartItem.objects.create(product=pro, quantity=request.POST['quantity'], user=request.user, total_price=d) return HttpResponseRedirect('/home') else: pro = Product.objects.get(slug=slug) form = CartForm() context_dict = {'p': pro, 'f': form} return render(request, 'prodet.html', context_dict)
def cart_edit(request,id): try: cart=Cart.objects.get(id=id) except Cart.DoesNotExist: raise Http404 if request.method =='POST': form = CartForm(request.POST,instance=cart) if form.is_valid(): cart.user = request.user.id cart.product_num = request.POST['product_num'] cart.price = request.POST['price'] cart.count = request.POST['count'] cart.save() return HttpResponseRedirect(reverse('cart_list')) else: form = CartForm(instance=cart) return TemplateResponse(request, 'cart/cart_edit.html',{'form': form, 'cart': cart})
def cart_add(request, product_id): if not Product.objects.filter(id=product_id).exists(): raise Http404 if request.method =='POST': form = CartForm(request.POST) if form.is_valid(): cart = Cart() cart.user = request.user.id cart.product_num = product_id cart.name = request.POST['name'] cart.price = request.POST['price'] cart.count = request.POST['count'] cart.save() else: form = CartForm() return TemplateResponse(request,'top/toppage.html')
def product_detail(request, id, slug): product = get_object_or_404(Product, id=id, slug=slug, available=True) cart_product_form = CartForm() context = { 'product': product, 'cart_product_form': cart_product_form, } return render(request, 'core/product/detail.html', context)
def cart_add(request, product_id): # 요청자의 session을 이용해 Cart 객체 생성 cart = Cart(request) # print('id(cart) in cart_add:', id(cart)) product = get_object_or_404(Product, id=product_id) # CartForm includes quantity and is_update # quantity: item quantity # is_update: determine whether it will be updated # -> it is only 'True' when cart_detail works form = CartForm(request.POST) if form.is_valid(): cd = form.cleaned_data cart.add(product=product, quantity=cd['quantity'], is_update=cd['is_update']) print(cd['is_update']) else: cart.add(product=product, quantity=1, is_update=False) return redirect('cart:cart_detail')
def product_detail(request, id, slug=None): cart_form = CartForm() product = get_object_or_404(Product, id=id, slug=slug, available=True) wishlist = Wishlist(request) if not slug: cart_form = CartForm(instance=product) # Check if the product is in wishlist otherwise set the wishlist form to None. if str(id) in wishlist.get_wishlist_session_content(): wishlist_form = None else: wishlist_form = WishlistForm({'product_id': id}) context = { 'product': product, 'cart_form': cart_form, 'wishlist_form': wishlist_form } return render(request, 'shop/product/details.html', context)
def map_function(p): pid = str(p.id) q = cart.cart[pid]['quantity'] return { 'product': p, 'quantity': q, 'total': p.price * q, 'form': CartForm(initial={ 'quantity': q, 'product_id': pid }) }
def product_detail(request, p_id): product_image = ProductImage.objects.select_related('product').get( product__id=p_id) cart_form = CartForm() r = Recommend() try: suggested_items = r.suggest_items(product_id=p_id)[:3] except Exception as e: suggested_items = None print(f'not connect redis:{e}') return render( request, 'shop/product/detail.html', { 'product_image': product_image, 'cart_form': cart_form, 'suggested_items': suggested_items })
def product_detail(request, product_id, product_slug): product = get_object_or_404(Product, id=product_id, slug=product_slug, available=True) similar_products = Product.objects.filter( category=product.category).exclude(id=product.id) form = CartForm() return render(request, 'products/detail.html', { 'product': product, 'similar_products': similar_products, 'form': form })
def product(request, product_id): product = get_object_or_404(Product, pk=product_id) images = product.image_set.all() sizes = product.size.all() # filter stock where amount is more than 0 for the selected product stock = Stock.objects.filter(product=product, amount__gt=0) # get available sizes for the product, remove duplicates and sort by size field sizes_available = sorted(set([item.size for item in stock]), key=lambda k: k.size) cart_form = CartForm() args = { 'product': product, 'images': images, 'sizes': sizes, 'sizes_available': sizes_available, 'cart_form': cart_form } return render(request, 'products/product.html', args)
def cart_detail(request): cart = Cart(request) product_list = list() for item in cart: # quantity 및 is_update 데이터를 담고 있는 폼을 cart-session에 저장 # item = {'1':{'quantity': 1, 'price': 10, cartform:<..., fields = (quantity, is_update)>}} item['cart_form'] = CartForm(initial={ 'quantity': item['quantity'], 'is_update': True }) product_list.append(item['product']) # print(item['cart_form']) item['image'] = ProductImage.objects.select_related('product').get( product=item['product']) product_images = ProductImage.objects.select_related('product').filter( product__in=product_list) # print(product_images) return render(request, 'cart/detail.html', { 'cart': cart, 'product_images': product_images })
def post(self, request, pk=None, *args, **kwargs): form = CartForm(request.POST) if form.is_valid(): try: item = Cart.objects.get_cart_item(self.get_object(), request.user) if item: messages.error(request, 'Item is already in your cart!') return redirect('/products') except Cart.DoesNotExist: item = form.save(commit=False) item.product = self.get_object() item.user = request.user form.save() messages.success(request, 'Item has been added to your cart!') return redirect('/products')
def product_detail(request, product_id): product = get_object_or_404(Product, pk=product_id) category_list = Category.objects.all() product_total_count = Product.objects.count() qna_list = Post.objects.filter(product=product) cart_form = CartForm() qnaform = QnaForm() review_form = ReviewForm() try: like = product.get_like(request.user) except: like = None if request.user.is_staff: answer_form = AnswerForm() else: answer_form = None if request.method == 'POST': form = QnaForm(request.POST) if form.is_valid(): qna = form.save(commit=False) qna.author = request.user qna.product = product qna.save() return redirect(product) return render( request, 'products/product_detail.html', { 'cart_form': cart_form, 'product': product, 'category_list': category_list, 'product_total_count': product_total_count, 'like': like, 'qnaform': qnaform, 'qna_list': qna_list, 'answer_form': answer_form, 'review_form': review_form, })
def htmlsave(request): form = CartForm(request.POST or None) if request.method == 'POST': form = CartForm(request.POST) if form.is_valid(): instance = form.save(commit=False) try: instance.save(request.user) context = { 'form': form, } return HttpResponse("good") except IndexError: return redirect('fail') print("여기") return redirect('fail') return HttpResponse("good")
def product_add_to_cart_view(request, pk): product = get_object_or_404(Product, id=pk) form = CartForm(request.POST or None) if form.is_valid(): try: cart_item = Cart.objects.get(product=pk, user=request.user) if cart_item: messages.error(request, 'Item is already in your cart!') return redirect('/products') except Cart.DoesNotExist: item = form.save(commit=False) item.product = product item.user = request.user form.save() messages.success(request, 'Item has been added to your cart!') return redirect('/products') context = { 'form': form, 'product': product } return render(request, 'products/product_add_to_cart.html', context)
def get(self, request, pk=None, *args, **kwargs): form = CartForm() context = {'form': form, 'product': self.get_object()} return render(request, 'products/product_add_to_cart.html', context)
def get_cart(req): form = CartForm() return render(req, 'pages/cart_page.html', { 'cart': Cart(req), 'form': form })
def cart_detail(request): """Show the cart info, and process the cart. """ cart_list = [] cart_content = request.COOKIES.get('ligucart', None) if cart_content: try: # Separamos las comas ',' que al ser leidas aca son '%2C' for element in cart_content.split('%2C'): amount, producto_id, product_price = element.split('_') product = Product.objects.get(pk=producto_id) cart_list.append({ 'amount': int(amount), 'product': product, 'subtotal': int(amount) * product.price, 'item_quantity': range(1, product.quantity + 1) }) except: # Si pasa algo raro borramos el listado cart_list = [] if request.method == 'POST': form = CartForm(request.POST) if form.is_valid(): order = Order.objects.create( customer_name=form.cleaned_data['name'][:100], customer_email=form.cleaned_data['email'], customer_phone=form.cleaned_data['phone'][:10], customer_address=form.cleaned_data['address'][:50], total=0, more_info=form.cleaned_data['message'][:100], ) total = 0 for content in cart_list: product = Product.objects.get(id=content['product'].id) product.quantity -= content['amount'] product.save() CartProduct.objects.create( order=order, product=content['product'], amount=content['amount'], ) total += int(content['subtotal']) order.total = total order.save() message = render_to_string('cart/cart_order_email.html', { 'name': order.customer_name, 'cart_list': cart_list, 'total': total, }) email_message = EmailMessage( u'[Ligu] Hemos recibido su orden de compra.', message, to=[order.customer_email], headers={'Reply-To': settings.EMAIL_REPLY_TO}, ) email_message.content_subtype = 'html' email_message.send() provider_emails = [] for product in cart_list: print(product['product'].created_by.email) if product['product'].created_by.email not in provider_emails: provider_emails.append(product['product'].created_by.email) for email in provider_emails: product_list = [] for product in cart_list: if email == product['product'].created_by.email: product_list.append(product) message = render_to_string('cart/cart_products_sold_email.html', { 'product_list': product_list, }) email_message = EmailMessage( u'[Ligu] Has vendido productos en Ligu!', message, to=[email], headers={'Reply-To': settings.EMAIL_REPLY_TO}, ) email_message.content_subtype = 'html' email_message.send() product_list = [] send_mail( u'[Notificación] Se ha generado un nuevo pedido', 'Se ha generado la orden numero: %s' % order.id, '*****@*****.**', settings.EMAIL_REPLY_TO, ) response = HttpResponseRedirect(reverse('cart:cart_complete')) response.delete_cookie('ligucart') return response else: form = CartForm() return render(request, 'cart/cart_detail.html', { 'form': form, 'cart_list': cart_list, })
def get(self, request): content = {'form': CartForm()} return render(request, 'cart/create_new_cart.html', content)
def edit_cart(request, id): instance = get_object_or_404(Product, id=id) cart_form = CartForm() context = {'instance': instance, 'cart_form': cart_form} return render(request, 'cart/edit_cart.html', context)
def test_form_is_valid(self): form = CartForm(data=self.data) self.assertTrue(form.is_valid())