def registration(request): """User registration""" if request.user.is_authenticated(): return redirect(reverse('index')) if request.method == 'POST': form = Registration(request.POST) if form.is_valid(): data = form.cleaned_data with transaction.atomic(): user = User( username=data['email'], first_name=data['first_name'], last_name=data['last_name'], email=data['email'], ) user.set_password(data['password']) user.save() customer = Customer( user=user, phone=data['phone'], patronymic=data['middle_name'], ) customer.save() return redirect(reverse('profile')) else: form = Registration() cart = Cart(request) context = { 'form': form, 'cart_count': cart.count(), } return render(request, 'accounts/create.html', context)
def update(request): """User profile update""" if not hasattr(request.user, 'customer'): raise Http404("user is not related with a customer") customer = request.user.customer if request.method == 'POST': form = Profile(request.POST) if form.is_valid(): data = form.cleaned_data with transaction.atomic(): user = customer.user user.first_name = data['first_name'] user.last_name = data['last_name'] user.email = user.username = data['email'] user.save() customer.patronymic = data['middle_name'] customer.phone = data['phone'] customer.save() return redirect(reverse('profile')) else: data = { 'first_name': customer.user.first_name, 'middle_name': customer.patronymic, 'last_name': customer.user.last_name, 'email': customer.user.email, 'phone': customer.phone, } form = Profile(data) cart = Cart(request) context = { 'customer': request.user.customer, 'form': form, 'cart_count': cart.count(), } return render(request, 'accounts/update.html', context)
def cart_remove(request, product_id): cart = Cart(request) product = get_object_or_404(Product, id=product_id) cart.remove(product) messages.info(request, _("You have removed {} from your cart.").format(product)) return redirect('shop:cart_detail')
def post(self, request, slug): cart = Cart(request) product = Product.objects.get(slug=slug) quantity = request.POST.get('quantity') options = ProductOptions.objects.filter( id__in=request.POST.getlist('options')) cart.add(product, options, quantity) return HttpResponse(status=200)
def show(request, id): """Product card page""" product = get_object_or_404(Product, pk=id) cart = Cart(request) context = { 'product': product, 'in_cart': cart.has(product), 'cart_count': cart.count(), } return render(request, 'sales/show.html', context)
def order(request, id): if not hasattr(request.user, 'customer'): raise Http404("user is not related with a customer") cart = Cart(request) order = get_object_or_404(Order, pk=id, customer=request.user.customer) context = { 'order': order, 'cart_count': cart.count(), } return render(request, 'sales/order.html', context)
def cart_add(request, product_id): cart = Cart(request) product = get_object_or_404(Product, id=product_id) form = CartAddProductForm(request.POST) if form.is_valid(): cd = form.cleaned_data cart.add(product=product, quantity=cd['quantity'], update_quantity=cd['update']) return redirect('cart_detail')
def add_cart(request, slug): cart = Cart(request) item = get_object_or_404(Item, slug=slug) form = CartAddProductForm(request.POST) if form.is_valid(): clean = form.cleaned_data cart.add(item=item, quantity=clean['quantity'], update_quantity=clean['update']) return redirect('cart_detail')
def orders(request): if not hasattr(request.user, 'customer'): raise Http404("user is not related with a customer") cart = Cart(request) orders = request.user.customer.order_set.all() context = { 'orders': orders, 'cart_count': cart.count(), } return render(request, 'sales/orders.html', context)
def profile(request): if not hasattr(request.user, 'customer'): LOGGER.error("user is not related with a customer") raise Http404("user is not related with a customer") cart = Cart(request) context = { 'customer': request.user.customer, 'cart_count': cart.count(), 'customer': request.user.customer, } return render(request, 'accounts/profile.html', context)
def cart_add(request, product_id): cart = Cart(request) product = get_object_or_404(Product, id=product_id) form = CartAddProductForm(request.POST) if form.is_valid(): cd = form.cleaned_data cart.add(product=product, quantity=cd['quantity'], update_quantity=cd['update']) messages.info(request, _("You have added {} to your cart.").format(product)) return redirect('shop:cart_detail')
def index(request): categories = Category.objects.all().order_by('name') # filter params: page, category, name category = None params = {'cat_url': [], 'page_url': []} products = Product.objects.all().order_by('-modified') # text search filter search = request.GET.get('name', '') if search: products = products.filter(name__icontains=request.GET['name']) params['cat_url'].append('name=' + request.GET['name']) params['page_url'].append('name=' + request.GET['name']) # categories filter try: if request.GET.get('cat'): category = Category.objects.get(pk=int(request.GET['cat'])) products = products.filter(category=category) params['page_url'].append('cat=' + str(category.id)) except (ValueError, Category.DoesNotExist) as err: LOGGER.error(err) # pagination filter paginator = Paginator(products, settings.PRODUCTS_ON_PAGE) page = request.GET.get('page', 1) try: products = paginator.page(page) except PageNotAnInteger: page = 1 products = paginator.page(page) except EmptyPage: page = paginator.num_pages products = paginator.page(page) params['cat_url'].append('page=' + str(page)) cart = Cart(request) context = { 'categories': categories, 'request': request, 'params': params, 'products': products, 'search': search, 'category': category, 'cart_count': cart.count(), } return render(request, 'sales/index.html', context)
def cart(monkeypatch): shop_settings = { 'charge': 0.00, 'bulk_charge': 10.00, 'quantity': 10 } monkeypatch.setattr(Cart, 'shop_settings', shop_settings) return Cart(request=Request())
def test_cart(self): url = f'/cart/add/{self.product.id}/' self.client.get(url, HTTP_X_REQUESTED_WITH='XMLHttpRequest') response = self.client.get('/cart/') self.assertEqual(response.status_code, 200) self.assertEqual(Cart(self.session_cart), response.context_data.get('cart'))
def test_cart_weight(self): c = Cart() # add to cart el producte 12, quantitat 1 c.add((12, None, 1)) weight = cart_weight(c) self.assertEqual(weight, 960) c.add((12, None, 2)) self.assertEqual(cart_weight(c), 960*3) c.add((11, None, 1)) self.assertEqual(cart_weight(c), (960*3)+(2800))
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 get(self, *args, **kwargs): cart = Cart(self.request) if len(cart) < 1: return redirect('cart') profile = Profile.objects.get(user=self.request.user) new_order = Order(customer=profile, status=0) new_order.save() # new_order.save() for item in cart: print(item) ordered_item = OrderItems( order=new_order, item=item['item'], price_on_order_date=item['item'].get_raw_price_with_discount, quantity=item['quantity']) ordered_item.save() # new_order.save() cart.clear() return redirect('orders')
def cart_detail(request): cart = Cart(request) print(cart) for item in cart: print(item) item['update_quantity_form'] = CartAddProductForm( initial={ 'quantity': item['quantity'], 'update': True }) return render(request, 'shop/detail.html', {'cart': cart})
def registration_complete(request, slug): pk = request.session.get("reg_id") registry = Registry.objects.get(pk=pk) event = registry.event order = Cart(request) meal_order_formset = None msgs = [] if event.offers_meals: meals = event.meals.all() meal_order_formset = ServiceOrderFormSet( request.POST or None, initial=[{"id":meal.id, "unit_price":meal.price, "name":meal.description} for meal in meals] ) if request.method == "POST": if meal_order_formset.is_valid(): meals_by_id = dict([[meal.id, meal] for meal in meals]) for form in meal_order_formset: quantity = int(form.cleaned_data['quantity']) if quantity > 0: meal_id = int(form.cleaned_data['id']) meal = meals_by_id[meal_id] try: order.add(meal, meal.price, quantity, meal.description) except OrderAlreadyCheckedout: return redirect("payment", order.cart.id) return redirect("checkout") return render(request, "evreg/registration_completed.html", {"registry": registry, "event": event, "meal_order_formset": meal_order_formset, "msgs": msgs, "order": order })
def test_order_from_cart(self): """ Tests that 1 + 1 always equals 2. """ self.assertEqual(1 + 1, 2) client = Client.objects.get(pk=1) self.assertEqual(client.email, '*****@*****.**') c = Cart() c.add((12, 37, 2)) c.add((1, None, 1)) l = cart_list(c) order = order_from_cart(c, client, 'paypal') self.assertEqual(len(order.line_set.all()), 3) # this test fails because not shipping costs ship_cost = Decimal(calc_shipping_costs(c, '08695', cart_total(l))) self.assertEqual(order.total(), cart_total(l) + ship_cost ) self.assertEqual(order.line_set.all()[2].types, 'ship' ) self.assertEqual(order.pay_type, 'paypal' )
def PaymentDone(request): order_id = request.session.get('order_id') order = get_object_or_404(Order, id=order_id) order.paid = True order.save() return render( request, 'payment/done.html', { 'w_categories': Category.objects.filter(gender='Women').order_by('-name')[0:8], 'm_categories': Category.objects.filter(gender='Men').order_by('-name')[0:8], 'brands': Brand.objects.order_by('-name')[0:8], 'cart': Cart(request), 'cart_len': len(Cart(request)), 'cupon_apply_form': CuponApplyForm(), 'order': order })
def cart_detail(request): cart = Cart(request) for item in cart: item['update_quantity_form'] = CartAddProductForm( initial={ 'quantity': item['quantity'], 'update': True }) coupon_apply_form = CouponApplyForm() return render(request, 'cart/detail.html', { 'cart': cart, 'coupon_apply_form': coupon_apply_form, })
def confirm(request): """It confirms a customer's order and sets delivery address """ if not hasattr(request.user, 'customer'): raise Http404("user is not related with a customer") customer = request.user.customer cart = Cart(request) if cart.is_empty(): # empty cart can't approve any order return redirect(reverse('index')) products = [] try: for product, count in cart.get().items(): product.count = count product.total = round(product.price * int(count), 2) products.append(product) except (ValueError,) as err: raise Http404(err) if request.method == 'POST': form = DeliveryForm(request.POST) form.set_choises(customer) if form.is_valid(): data = form.cleaned_data with transaction.atomic(): if data['new']: # create new delivery address delivery = Delivery( customer=customer, address=data['new'], ) delivery.save() else: # use existed address delivery = get_object_or_404(Delivery, pk=data['existed']) order = Order( customer=customer, desc=data['comment'], ) order.save() for product in products: ProductSet.objects.create( product=product, order=order, number=product.count, ) return cart.clean(redirect(reverse('order', args=[order.id]))) else: form = DeliveryForm() form.set_choises(customer) context = { 'products': products, 'cart_count': cart.count(), 'total': cart.total(), 'form': form, } return render(request, 'sales/confirm.html', context)
def PaymentProcess(request): order_id = request.session.get('order_id') order = get_object_or_404(Order, id=order_id) host = request.get_host() paypal_dict = { 'business': settings.PAYPAL_RECEIVER_EMAIL, 'amount': '%.2f' % order.get_total_cost(), 'item_name': 'Order {}'.format(order.id), 'invoice': str(order.id), 'currency_code': 'USD', 'notify_url': 'http://{}{}'.format(host, reverse('paypal:paypal-ipn')), 'return_url': 'http://{}{}'.format(host, reverse('payment:done')), 'cancel_return': 'http://{}{}'.format(host, reverse('payment:canceled')) } form = PayPalPaymentsForm(initial=paypal_dict) return render( request, 'payment/process.html', { 'order': order, 'form': form, 'w_categories': Category.objects.filter(gender='Women').order_by('-name')[0:8], 'm_categories': Category.objects.filter(gender='Men').order_by('-name')[0:8], 'brands': Brand.objects.order_by('-name')[0:8], 'cart': Cart(request), 'cart_len': len(Cart(request)), 'cupon_apply_form': CuponApplyForm() })
def order_create(request): cart = Cart(request) if request.method == 'POST': form = OrderCreateForm(request.POST) if form.is_valid(): order = form.save(commit=False) if cart.coupon: order.coupon = cart.coupon order.discount = cart.coupon.discount order.user = request.user order.order_number = get_random_string( 10, allowed_chars=string.ascii_uppercase + string.digits) order.save() for item in cart: OrderItem.objects.create(order=order, product=item['product'], price=item['price'], quantity=item['quantity']) cart.clear() send_order_creat_email(order) return render(request, 'order/created.html', {'order': order}) else: form = OrderCreateForm() return render(request, 'order/create.html', {'cart': cart, 'form': form})
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 OrderCreate(request): if request.method == 'POST': form = OrderCreateForm(request.POST) if form.is_valid(): order = form.save() if Cart(request).cupon: order.cupon = Cart(request).cupon order.discount = Cart(request).cupon.discount order.save() for item in Cart(request): OrderItem.objects.create(order=order, product=item['product'], price=item['price'], color=item['color'], size=item['size']) product = item['product'] product.stock -= 1 if product.stock is 0: product.available = False product.save() Cart(request).clear() request.session['order_id'] = order.id return redirect(reverse('payment:process')) form = OrderCreateForm() return render( request, 'orders/create.html', { 'w_categories': Category.objects.filter(gender='Women').order_by('-name')[0:8], 'm_categories': Category.objects.filter(gender='Men').order_by('-name')[0:8], 'brands': Brand.objects.order_by('-name')[0:8], 'cart': Cart(request), 'cart_len': len(Cart(request)), 'cupon_apply_form': CuponApplyForm() })
def test_order_from_cart(self): """ Tests that 1 + 1 always equals 2. """ self.assertEqual(1 + 1, 2) client = Client.objects.get(pk=1) self.assertEqual(client.email, '*****@*****.**') c = Cart() c.add((12, 37, 2)) c.add((1, None, 1)) l = cart_list(c) order = order_from_cart(c, client, 'paypal') self.assertEqual(len(order.line_set.all()), 3) # this test fails because not shipping costs ship_cost = Decimal(calc_shipping_costs(c, '08695', cart_total(l))) self.assertEqual(order.total(), cart_total(l) + ship_cost) self.assertEqual(order.line_set.all()[2].types, 'ship') self.assertEqual(order.pay_type, 'paypal')
def get_context_data(self, **kwargs): context_data = super(CartView, self).get_context_data(**kwargs) context_data['cart'] = Cart(self.request) return context_data
def cart_remove(request, product_id): cart = Cart(request) product = get_object_or_404(Product, id=product_id) cart.remove(product) return redirect('cart_detail')
from shop.cart import Cart from drawn import Drawn from random import choice Drawn('http://www.wp.pl') c = Cart() c.add(Drawn('http://www.amazon.co.uk/Doctor-Who-50th-Anniversary-Special/dp/B00F37VHX4/ref=pd_cp_d_h__0')) c.add(Drawn('http://www.amazon.co.uk/Star-Wars-Original-Trilogy-Episodes/dp/B00E0NHP6K/ref=br_lf_m_1000772753_1_2_img?ie=UTF8&s=dvd&pf_rd_p=453915507&pf_rd_s=center-2&pf_rd_t=1401&pf_rd_i=1000772753&pf_rd_m=A3P5ROKL5A1OLE&pf_rd_r=0S4X8JSW469NW7P9RQ7B')) c.add(Drawn('http://www.amazon.com/Star-Trek-VIII-First-Contact/dp/B000IZ8SD8/ref=pd_sim_mov_aiv_7')) #print c.elements[0].item.title for element in c.elements: print element.item.title, element.item.price print "Wybralem dla Ciebie" el = choice(c.elements) print el.item.title
def cart_remove(request, slug): cart = Cart(request) item = get_object_or_404(Item, slug=slug) cart.remove(item) return redirect('cart_detail')
def post(self, request, *args, **kwargs): def _get_total_price(ordered_products): total_price = 0 for ordered_product in ordered_products: total_price += ordered_product.total return total_price if request.user.is_authenticated: cart = CartAuth(request) else: cart = Cart(request) order_form = OrderForm(request.POST) if order_form.is_valid(): fullname = order_form.cleaned_data['fullname'] email = order_form.cleaned_data['email'] phone = order_form.cleaned_data['phone'] user = None if request.user.is_authenticated: user = request.user elif User.objects.get(username=email).exists(): return redirect(reverse('account:login')) else: password = User.objects.make_random_password() user = User.objects.create_user(email, email, password) profile = Profile(user=user, phone=phone) profile.save() user.last_name = fullname postcode = order_form.cleaned_data.get('postcode') region = order_form.cleaned_data.get('region') area = order_form.cleaned_data.get('area') city = order_form.cleaned_data.get('city') street = order_form.cleaned_data.get('street') house = order_form.cleaned_data.get('house') building = order_form.cleaned_data.get('building') apartment = order_form.cleaned_data.get('apartment') comment = order_form.cleaned_data.get('comment') payment_type = order_form.cleaned_data.get('payment_type') entity_name = order_form.cleaned_data.get('entity_name') entity_inn = order_form.cleaned_data.get('entity_inn') entity_kpp = order_form.cleaned_data.get('entity_kpp') delivery = None entity = None if postcode: delivery = Delivery(postcode=postcode, region=region, area=area, city=city, street=street, house=house, building=building, apartment=apartment, comment=comment) delivery.save() if entity_name: entity = Entity(title=entity_name, inn=entity_inn, kpp=entity_kpp) entity.save() order = Order(delivery=delivery, user=user, entity=entity) order.save() products = tuple(cart.get()) print(tuple(products), 'ORDER PRODUCTS FOR CREATE') ordered_products = OrderedProducts.objects.bulk_create( OrderedProducts(order=order, product=product, count=product.count, total=product.get_discount_price() * int(product.count)) for product in products) if payment_type in ('bank', 'bill', 'receipt'): payment = Payment(total=_get_total_price(ordered_products), _type=self.payment_type_crutch[payment_type]) payment.save() order.payment = payment order.save() return redirect(reverse('account:ProfileOrders')) return redirect(reverse('account:ProfileOrders'))
def post(self, request, *args, **kwargs): action_type = request.POST.get('action') if action_type is not None: data = dict() if action_type == 'compare': add_pk = request.POST.get('add', None) remove_pk = request.POST.get('remove', None) if add_pk is not None and add_pk.isdigit(): if request.user.is_authenticated: compare = CompareAuth(request) else: compare = Compare(request) compare.add(add_pk) data['compare_count'] = len(compare) elif remove_pk is not None and remove_pk.isdigit(): if request.user.is_authenticated: compare = CompareAuth(request) else: compare = Compare(request) compare.remove(remove_pk) context = dict() compare_len = len(compare) context['compare_count'] = compare_len context['id'] = remove_pk if compare_len == 0: return JsonResponse({ 'empty': get_template('compare_empty.html').render( context=None, request=request), 'compare_count': compare_len, }) else: return JsonResponse(context) elif action_type == 'favorites': add_pk = request.POST.get('add', None) remove_pk = request.POST.get('remove', None) if add_pk is not None and add_pk.isdigit(): if request.user.is_authenticated: favorites = FavoritesAuth(request) else: favorites = Favorites(request) favorites.add(add_pk) data['favorites_count'] = len(favorites) elif remove_pk is not None and remove_pk.isdigit(): if request.user.is_authenticated: favorites = FavoritesAuth(request) else: favorites = Favorites(request) favorites.remove(remove_pk) context = dict() favorites_len = len(favorites) context['favorites_count'] = favorites_len context['id'] = remove_pk if favorites_len == 0: return JsonResponse({ 'empty': get_template('favorites_empty.html').render( context=None, request=request), 'favorites_count': favorites_len, }) else: return JsonResponse(context) elif action_type == 'cart': add_pk = request.POST.get('add', None) count = request.POST.get('count', None) update_pk = request.POST.get('update', None) remove_pk = request.POST.get('remove', None) if add_pk is not None and add_pk.isdigit(): if request.user.is_authenticated: cart = CartAuth(request) else: cart = Cart(request) if count is not None and count.isdigit(): cart.add(add_pk, count) else: cart.add(add_pk) data['cart_count'] = len(cart) elif remove_pk is not None and remove_pk.isdigit(): if request.user.is_authenticated: cart = CartAuth(request) else: cart = Cart(request) cart.remove(remove_pk) context = dict() cart_len = len(cart) context['cart_count'] = cart_len context['id'] = remove_pk if cart_len == 0: return JsonResponse({ 'empty': get_template('cart_empty.html').render( context=None, request=request), 'cart_count': cart_len, }) else: return JsonResponse(context) elif update_pk is not None and update_pk.isdigit(): count = request.POST.get('count', None) if count is not None and count.isdigit(): if request.user.is_authenticated: cart = CartAuth(request) else: cart = Cart(request) cart.update_count(update_pk, count) return JsonResponse(data)
def main_data(request): return {"categories": Category.objects.all(), 'cart': Cart(request)}
def get_bag(request): cart = Cart(request) bag_quantity = len(cart) if not bag_quantity: bag_quantity = '' return {'bag_quantity': bag_quantity, 'cart': iter(cart)}
def test_cart_list(self): c = Cart() # add to cart el producte 12, quantitat 1 c.add((12, None, 1)) l = cart_list(c) # afegeix b el producte self.assertEqual( 12, l[0][0].pk ) # retorna la quantitat de forma correcta self.assertEqual( 1, float(l[0][2]) ) # retorna el preu correctament self.assertEqual( 24.9, float(l[0][3]) ) # probem amb dos lines amb el mateix producte, ha d'afegir descmpte per quantitat c.add((12, None, 1)) l = cart_list(c) self.assertEqual( 24.9, float(l[0][3]) ) self.assertEqual( 44.9/2, float(l[0][4]) ) # testem que el total d'items de c funciona self.assertEqual( c.total_items(), 2 ) c.add((12, None, 3)) l = cart_list(c) self.assertEqual( c.total_items(), 5 ) self.assertEqual( c.total(), 3 ) self.assertEqual( 79.9/4, float(l[2][4]) ) self.assertEqual( round((79.9/4)*3, 2), round(float(l[2][5]), 2) )
def widget_cart(request): cart = Cart(request) return {'cart': cart}
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')))
def process_request(self, req): c = Cart(req) req.cart = c
def cart(request): return {'cart': Cart(request)}