def get(self, request): cart = Cart(request) offer_id = request.GET.get('offer_id') offer = get_object_or_404(Offer, pk=offer_id) cart.remove(offer.id) return redirect('cart')
def __init__(self, key, type_participant, game): self.key = key self.type = 'user' if type_participant == 1 else 'computer' self.game = game self.cart = Cart() self.can_play = True self.winner = False
def get(request, category_slug, subcategory_slug, product_slug): product = get_object_or_404(Product, slug=product_slug) offer = product.offers.first() product_price = offer.price if offer else product.price in_stock = offer.in_stock if offer else product.in_stock category = get_object_or_404(Category, slug=category_slug) if subcategory_slug != 'all': subcategory = get_object_or_404(SubCategory, slug=subcategory_slug) else: subcategory = None cart = Cart(request) in_cart = str(product.id) in cart.keys() context = { 'product': product, 'offer': offer, 'product_price': product_price, 'in_stock': in_stock, 'in_cart': in_cart, 'category': category, 'subcategory': subcategory, } return render(request, 'products/catalogue-item.html', context)
def get(self, request): cart = Cart(request) offer_id = request.GET.get('offer_id') quantity = request.GET.get('quantity', 1) offer = get_object_or_404(Offer, pk=offer_id) cart.change_quantity(offer.id, int(quantity)) return redirect('cart')
def get(request): product_id = request.GET.get('product_id') cart = Cart(request) cart.remove(product_id) context = { 'cart_len': len(cart), } return JsonResponse(context)
def post(self, *args, **kwargs): cart = Cart(self.request) item = get_object_or_404(Item, id=kwargs['pk']) form = CartAddForm(self.request.POST) if form.is_valid(): cd = form.cleaned_data cart.add(item=item, quantity=cd['quantity'], update_quantity=cd['update']) return redirect("ordersummary")
def get(self, request, order_id): order = Order.objects.get(pk=order_id) if order.pay_type == 'online': order.status = 'paid' order.save() cart = Cart(request) cart.clear() send_order_mail(request, order) context = {'order': order} return render(request, 'orders/order-done.html', context)
def get(request): product_id = request.GET.get('product_id') quantity = int(request.GET.get('quantity')) cart = Cart(request) cart.change_quantity(product_id, quantity) cost = '{:,}'.format(cart.cart[product_id]['cost']).replace(',', ' ') context = { 'cart_len': len(cart), 'cost': cost, } return JsonResponse(context)
def get(request): product_id = int(request.GET.get('product_id')) price = int(request.GET.get('price').replace(' ', '')) quantity = int(request.GET.get('quantity')) max_q = int(request.GET.get('max_q')) bar_type = request.GET.get('bar_type') product = get_object_or_404(Product, id=product_id) cart = Cart(request) cart.add(product, price, quantity, max_q, bar_type) context = { 'cart_len': len(cart), } return JsonResponse(context)
def get(self, request): cart = Cart(request) # if not cart.delivery['price']: # messages.error(request, 'Неверный почтовый индекс') user = request.user initial = cart.delivery if user.is_authenticated: initial = { 'method': cart.delivery['method'], 'price': cart.delivery['price'], # 'postcode': cart.delivery['postcode'] or user.postcode, 'country': cart.delivery['country'] or user.country, 'region': cart.delivery['region'] or user.region, 'city': cart.delivery['city'] or user.city, 'micro_district': cart.delivery['micro_district'] or user.micro_district, 'street': cart.delivery['street'] or user.street, 'house_nmb': cart.delivery['house_nmb'] or user.house_nmb, 'building_nmb': cart.delivery['building_nmb'] or user.building_nmb, 'room_nmb': cart.delivery['room_nmb'] or user.room_nmb, 'phone': cart.delivery['phone'] or user.phone, 'full_name': cart.delivery['full_name'] or user.full_name, 'email': cart.delivery['email'] or user.email, } order_form = OrderForm(initial=initial) context = { 'order_form': order_form, } return render(request, 'orders/cart.html', context)
def get(self, request): cart = Cart(request) product_id = request.GET.get('product') color_id = request.GET.get('color') or None size_id = request.GET.get('size') or None cup_id = request.GET.get('cup') or None offer = get_object_or_404(Offer.objects.select_related( 'color', 'size', 'cup'), product__id=product_id, is_active=True, color=color_id, size=size_id, cup=cup_id) cart.add(offer.id) return redirect(request.META.get('HTTP_REFERER'))
def get(request): cart = Cart(request) order_form = OrderForm() context = { 'cart': list(cart), 'order_form': order_form, } return render(request, 'orders/cart.html', context)
def post(request): order_form = OrderForm(request.POST) cart = Cart(request) if order_form.is_valid(): try: new_order = order_form.save(commit=False) new_order.total_price = cart.get_total_price() new_order.save() for item in cart: product = Product.objects.get(id=int(item['product_id'])) OrderItem.objects.create(order=new_order, product=product, price=item['price'], quantity=item['quantity'], total_price=item['cost'], bar_type=item['bar_type']) current_site = get_current_site(request) mail_subject = 'Новый заказ на сайте: ' + current_site.domain message = render_to_string('email_messages/order_message.html', { 'domain': current_site.domain, 'order': new_order, }) to_email = MailToString.objects.first().email email = EmailMessage(mail_subject, message, to=[to_email]) email.send() cart.clear() status = 1 except Exception as e: print(e) status = 0 else: status = 0 context = { 'status': status, } return JsonResponse(context)
def decrease_quantity(request, pk): cart = Cart(request) item = get_object_or_404(Item, id=pk) item_id = str(item.id) print(cart.__dict__) if cart.cart[item_id]['quantity'] > 1: cart.add(item=item, quantity=-1) else: cart.remove(item) return redirect("ordersummary")
def post(self, *args, **kwargs): cart = Cart(self.request) order, created = Order.objects.get_or_create(user=self.request.user, ordered=False) item_ids = cart.cart.keys() items = Item.objects.filter(id__in=item_ids) for item in items: quantity = cart.cart[str(item.id)]['quantity'] order_item, created = OrderItem.objects.get_or_create( item=item, user=self.request.user, ordered=False, quantity=quantity) order.items.add(order_item) form = CheckoutForm(self.request.POST or None) if form.is_valid(): street_address = form.cleaned_data.get('street_address') apartment_address = form.cleaned_data.get('apartment_address') country = form.cleaned_data.get('country') zip = form.cleaned_data.get('zip') # TODO add funtionality for these fields # same_shipping_address = form.cleaned_data.get('same_shipping_address') # save_info form.cleaned_data.get('save_info') payment_option = form.cleaned_data.get('payment_option') billing_address = BillingAddress( user=self.request.user, street_address=street_address, apartment_address=apartment_address, country=country, zip=zip) billing_address.save() order.billing_address = billing_address order.save() print(payment_option) if payment_option == 'stripe': return redirect('payment', payment_option='stripe') elif payment_option == 'paypal': return redirect('payment', payment_option='paypal') else: messages.warning(self.request, 'Invalid payment option selected') return redirect('checkout')
def context_info(request): seo_titles = TitleTag.objects.all() index_info = Index.objects.first() main_phone = index_info.phone if index_info else None categories = Category.objects.all() cart = Cart(request) context = { 'seo_titles': seo_titles, 'main_phone': main_phone, 'categories': categories, 'cart_len': len(cart), } return context
def context_info(request): if 'admin' in request.META['PATH_INFO']: return {} socials = Social.objects.all() drop_pages = Page.objects.filter(is_active=True, action='dropdown') top_menu = Page.objects.filter(is_active=True, parent=None) whatsapp = Social.objects.filter(name__icontains='whatsapp').first() categories = Category.objects.all() seo_titles = TitleTag.objects.filter(url=request.path).first() try: index = Index.objects.first() except: index = Index.objects.none() try: contact_info = ContactInfo.objects.first() except: contact_info = ContactInfo.objects.none() favorite_count = FavoriteProduct.objects.filter( user=request.user).count() if request.user.is_authenticated else 0 login_form = LoginForm() register_form = RegisterForm() cart = Cart(request) context = { 'cart': cart, 'login_form': login_form, 'register_form': register_form, 'socials': socials, 'drop_pages': drop_pages, 'contact_info': contact_info, 'whatsapp': whatsapp, 'top_menu': top_menu, 'index': index, 'favorite_count': favorite_count, 'categories': categories, 'seo_titles': seo_titles, } return context
def get(self, request): cart = Cart(request) delivery_method = request.GET.get('delivery') city_name = request.GET.get('city') price = None if delivery_method == 'pochta': price = DeliveryMethod.objects.filter(name='pochta').first().price elif delivery_method == 'cdek_point': price = calc_cdeck_delivery(city_name, 368) elif delivery_method == 'cdek_home': price = calc_cdeck_delivery(city_name, 137) if price is None: cart.change_delivery(None, 0, request.GET) messages.error( request, 'Доставка по этому адрессу недоступна. Перепроверьте введенные данные или свяжитесь с нами.' ) return redirect('cart') cart.change_delivery(delivery_method, price, request.GET) return redirect('cart')
def get(self, request): code = request.GET.get('promocode') cart = Cart(request) promocode = cart.set_promocode(code) return redirect('cart')
def ordersummary(request): cart = Cart(request) total_cart_price = sum(item['final_item_price'] for item in cart) context = {'cart': cart, 'total_cart_price': total_cart_price} return render(request, 'ordersummary.html', context)
def get(self, *args, **kwargs): cart = Cart(self.request) item = get_object_or_404(Item, id=kwargs['pk']) cart.add(item=item) return redirect("ordersummary")
def remove_from_cart(request, pk): cart = Cart(request) item = get_object_or_404(Item, id=pk) cart.remove(item) return redirect("ordersummary")
def cart_item_count(request): cart = Cart(request) if hasattr(cart, 'cart'): return len(cart.cart) return 0
def local_cart(): cart = Cart() cart.number_on_cart = NUMBER_ON_CART.copy() cart.cart_numbers = CART_NUMBERS return cart
def test_format_number(self): cart = Cart() assert " ̶5" == cart.format_number(5)
def cart(request): return {'cart': Cart(request)}
class Participant: def __init__(self, key, type_participant, game): self.key = key self.type = 'user' if type_participant == 1 else 'computer' self.game = game self.cart = Cart() self.can_play = True self.winner = False @staticmethod def get_answer(): """Получение ответа игрока""" answers = [1, 2] cross_out = int(input('Зачеркнуть число(1) или продолжить(2): ')) while cross_out not in answers: print('Введите корректный ответ') cross_out = int(input('Зачеркнуть число(1) или продолжить(2): ')) return True if cross_out == answers[0] else False def act(self, number): """Действие игрока""" self.cart.print_cart() action = { 'computer': self.act_computer, 'user': self.act_man } return action[self.type](number) def check_status(self): """Проверка статуса игрока""" if self.winner: cprint(f"Игрок {self.key + 1} победил!", 'cyan') self.game.status = False elif not self.can_play: self.game.count_participants -= 1 def act_computer(self, number): """Действие компьютера""" if number in self.cart.number_on_cart: self.cart.cross_out(number) if len(self.cart.number_on_cart) == 0: self.winner = True def act_man(self, number): """Действие игрока""" if self.get_answer(): answer = self.cart.cross_out(number) if answer: if len(self.cart.number_on_cart) == 0: self.winner = True else: self.lose_game() else: if number in self.cart.number_on_cart: self.lose_game() def lose_game(self): """Проигрыш игрока""" self.can_play = False cprint('Вы проиграли', 'red') time.sleep(2)
def get(self, request): cart = Cart(request) promocode = cart.set_promocode(None) return redirect('cart')
def get(self, request): product_id = request.GET.get('product') color_id = request.GET.get('color') size_id = request.GET.get('size') cup_id = request.GET.get('cup') btn_type = request.GET.get('btn_type') product = Product.objects.get(pk=product_id) sizes, colors, cups = [], [], [] offer = Offer.objects.filter(product__id=product_id, color__id=color_id, size__id=size_id, cup__id=cup_id, is_active=True).first() if btn_type == 'color': if not offer: offer = Offer.objects.filter(product__id=product_id, color__id=color_id, is_active=True).first() for size in product.get_sizes(color_id=offer.color.id): checked = 1 if offer.size == size else 0 sizes.append((size.id, size.name, checked)) for cup in product.get_cups(color_id=offer.color.id, size_id=offer.size.id): checked = 1 if offer.cup == cup else 0 cups.append((cup.id, cup.name, checked)) elif btn_type == 'size': if not offer: offer = Offer.objects.filter(product__id=product_id, size__id=size_id, color__id=color_id, is_active=True).first() for cup in product.get_cups(color_id=offer.color.id, size_id=offer.size.id): checked = 1 if offer.cup == cup else 0 cups.append((cup.id, cup.name, checked)) elif btn_type == 'cup': pass try: image_id = offer.get_image().id except: image_id = None cart = Cart(request) in_cart = 1 if str(offer.id) in cart.cart else 0 offer_stock = 0 if offer.stock > 10: offer_stock = 'Много' elif offer.stock > 0 and offer.stock < 10: offer_stock = 'Мало' promo_text = None if offer.promotion_sale: promo_text = offer.promotion_sale.text elif offer.promotion_min_present: promo_text = offer.promotion_min_present.text elif offer.promotion_sum_present: promo_text = offer.promotion_sum_present.text elif offer.promotion_three_sales: promo_text = offer.promotion_three_sales.text context = { 'success': True, 'btn_type': btn_type, 'sizes': sizes, 'colors': colors, 'cups': cups, 'product_price': offer.product.price, 'offer_price': offer.get_price(), 'offer_stock': offer_stock, 'image_id': image_id, 'in_cart': in_cart, 'promo_text': promo_text, } return JsonResponse(context)
def post(self, request): order_form = OrderForm(request.POST) pay_type = request.POST.get('pay-type') cart = Cart(request) user = request.user if order_form.is_valid(): order = order_form.save() order_items = [] for item in cart: offer = item['offer'] if item['has_present']: order_item = OrderItem(order=order, offer=offer, price=item['price'], discount=item['price'], total_price_with_sale=0, quantity=1) order_items.append(order_item) if item['quantity'] - 1: order_item = OrderItem( order=order, offer=offer, price=item['price'], discount=item['cost'] - item['cost_with_sale'] - item['price'], total_price_with_sale=item['cost_with_sale'], quantity=item['quantity'] - 1) order_items.append(order_item) else: order_item = OrderItem( order=order, offer=offer, price=item['price'], discount=item['cost'] - item['cost_with_sale'], total_price_with_sale=item['cost_with_sale'], quantity=item['quantity']) order_items.append(order_item) offer.stock -= int(item['quantity']) order.delivery_price = int(cart.delivery['price']) order.total_price = cart.offers_price + int(cart.delivery['price']) order.total_price_with_sale = cart.get_total_price() order.user = user if user.is_authenticated else None order.pay_type = pay_type order.save() OrderItem.objects.bulk_create(order_items) Offer.objects.bulk_update(cart.offers, ['stock']) if pay_type == 'online': form_url = order_pay_response(request, order) elif pay_type == 'credit': form_url = order_pay_credit(request, order) return redirect(form_url) else: messages.error(request, 'Заполните все поля правильно') context = { 'order_form': order_form, } return render(request, 'orders/cart.html', context)