当前位置: 首页>>代码示例>>Python>>正文


Python cart.Cart类代码示例

本文整理汇总了Python中cart.Cart的典型用法代码示例。如果您正苦于以下问题:Python Cart类的具体用法?Python Cart怎么用?Python Cart使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Cart类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: clean_discount

    def clean_discount(self):
        discount = self.cleaned_data['discount'] or None
        if discount:
            if discount > self.request.user.bonus_score:
                raise forms.ValidationError(
                    _("You can not spend more bonus points than you have")
                )
            cart = Cart(self.request)
            price = cart.get_total_price()
            threshold = settings.DEFAULT_BONUS_PAY_THRESHOLD_AMOUNT
            exchange = settings.DEFAULT_EXCHANGE_RATE

            msg = _(
                """Maxium discount you can get
                is '%(percent)s' of '%(amount)s is %(max)s'""") % {
                'percent': str(threshold * 100) + '%',
                'amount': price,
                'max': str(round(price * Decimal(str(threshold))))
            }
            if Decimal(str(discount * exchange)) > (price * Decimal(str(threshold))):
                raise forms.ValidationError(msg)
            if discount < 0:
                raise forms.ValidationError(
                    _("You can not proceed negative values for discount")
                )
        return discount
开发者ID:stden,项目名称:colortek,代码行数:26,代码来源:forms.py

示例2: order_repeat

def order_repeat(request, pk):
    order = get_object_or_404(Order, pk=pk)
    containers = order.order_container_order_set.all()
    cart = Cart(request)
    if cart.cart.item_set.count() != 0:
        messages.error(
            request, _("You can not repeat order if there's something "
                       "in the cart, please cleanse it")
        )
        # return redirect(request.META.get('HTTP_REFERER', '/'))
        return redirect(reverse('catalog:service-page',
                                args=(order.container.owner.pk,)))
    for container in containers:
        model_class = container.content_type.model_class()
        item = get_object_or_None(
            model_class.whole_objects, pk=container.object_id
        )
        if item.is_deleted:
            messages.warning(
                request, _("Item '%s' does not exist anymore, sorry") % \
                         item.title
            )
        else:
            cart.add(item, item.get_cost(), container.quantity)
            # return redirect(request.META.get('HTTP_REFERER', '/'))
    return redirect(reverse('catalog:service-page',
                            args=(order.container.owner.pk,)))
开发者ID:stden,项目名称:colortek,代码行数:27,代码来源:views.py

示例3: add_item_to_cart

def add_item_to_cart(request, item_pk, quantity=1, checkout=False):
    cart = Cart(request)
    item = get_object_or_404(Item, pk=item_pk)
    # checking input data, validate it and raise error if something
    # goes unusual, without any data post for time measure resons
    threshold = item.category.threshold
    try:
        quantity = int(quantity)
    except TypeError:
        raise Http404("Go fsck yourself")
    if int(quantity) < threshold:
        msg = _("You can not order less of item quantity then "
                "given threshold"
        )
        return {'success': False, 'errors': unicode(msg)}
    if int(quantity) % threshold != 0:
        msg = _(
            "Quantity should be proportional to its item category threshold, "
            "you can not add items without it"
        )
        return {'success': False, 'errors': unicode(msg)}
    ct = ContentType.objects.get(
        app_label=Item._meta.app_label,
        model=Item._meta.module_name)
    try:
        cart.add(item, item.get_cost(), quantity)
    except ItemAlreadyExists:
        cart_item = cart.cart.item_set.get(object_id=item_pk, content_type=ct)
        if checkout:
            cart_item.quantity = quantity
        else:
            cart_item.quantity += quantity
        cart_item.save()
        return {'redirect': 'catalog:cart'}
    return {'redirect': request.META.get('HTTP_REFERER', '/')}
开发者ID:stden,项目名称:colortek,代码行数:35,代码来源:views.py

示例4: remove_from_cart

def remove_from_cart(request):
    product_id = request.POST['product_id']
    kw = get_kwrgs(request)
    product = Product.objects.get(id=product_id)
    cart = Cart(request)
    cart.remove(product)
    return render(request, 'shop/cart.html', kw)
开发者ID:Adviser-ua,项目名称:blueberry,代码行数:7,代码来源:views.py

示例5: checkout

def checkout(request):
    template_name='cart/checkout.html'
    pp_urls=None
    model=None
    '''
    Renders a form ready to be submit to paypal. Passes PAYPAL_URL, which is
    taken from settings. Also passes total, which is the total amount
    of all the cart items
    '''
#    cart=Cart.objects.get(user=request.user)
    cartModel=models.Cart.objects.get(user=request.user)
#    cartModel.user=request.user
    print 'test'
    print 'username is'+ request.user.username + request.user.id
#    print cartModel.id
    cart=Cart(request)
    items = Item.objects.filter(cart=cart)
    if model:
        ct = ContentType.objects.get_for_model(model)
        items = items.filter(content_type=ct)
    form = CheckoutForm(items, pp_urls)
    total = cart.total()
#    for item in items:
#        total += item.amount
    return render_to_response(template_name,{
            "form":form,
            "PAYPAL_URL": settings.PAYPAL_URL,
            "total": total,
            },context_instance=RequestContext(request))
开发者ID:HeisSuperHan,项目名称:djangoShop,代码行数:29,代码来源:views.py

示例6: delete_cart

def delete_cart(request, id):
    cart = Cart(request)
    cart.delete(id)
    if request.META.get('HTTP_X_REQUESTED_WITH', '') == 'XMLHttpRequest':
        return HttpResponse(cart.serialize())
    else:
        return redirect(reverse('show_cart'))
开发者ID:Sergey-L,项目名称:v2,代码行数:7,代码来源:views.py

示例7: clean

    def clean(self):
        # deliver_date, deliver_time
        dd = self.cleaned_data.get('deliver_date', None)
        dt = self.cleaned_data.get('deliver_time', None)

        cart = Cart(self.request)
        total_price = cart.get_total_price()
        item_ct = get_model_content_type(Item)
        item = cart.cart.item_set.filter(content_type=item_ct)

        minimal_cost = item[0].product.container.owner.minimal_cost if len(item) else 0
        if total_price < minimal_cost and total_price > 0:
            msg = _("Minimal cost for order is '%s' for this service, "
            "you should get more items to process") % minimal_cost
            self._errors['name'] = ErrorList([msg])

        if all((dd, dt)):
            now = datetime.now()
            offset = now + timedelta(minutes=30)
            st = datetime(dd.year, dd.month, dd.day, dt.hour, dt.minute, dt.second)
            if st <= offset:
                msg = _("You can not order in the past")
                self._errors['deliver_date'] = ErrorList([msg])

        return self.cleaned_data
开发者ID:stden,项目名称:colortek,代码行数:25,代码来源:forms.py

示例8: test_add_with_quantity_to_existing_item

 def test_add_with_quantity_to_existing_item(self):
     '''Adding an item with a quantity increases the quantity of an
     existing item.'''
     cart = Cart()
     cart.add('apple', 2)
     cart.add('apple', 3)
     self.assertEqual(cart.get_item('apple').quantity, 5)
开发者ID:brew,项目名称:cart-exercise,代码行数:7,代码来源:tests.py

示例9: test_add_two_same_item

 def test_add_two_same_item(self):
     '''Adding more than one of the same item does not create duplicate
     CartItems.'''
     cart = Cart()
     cart.add('apple')
     cart.add('apple')
     self.assertEqual(len(cart), 1)
开发者ID:brew,项目名称:cart-exercise,代码行数:7,代码来源:tests.py

示例10: make_order

def make_order(request):
    cart = Cart(request)
    user = request.user
    order = None
    if not user.is_authenticated():
        order = Order(client_name=u'Не зарегистрирован, ' + request.POST["name"], client_phone=request.POST["phone"], order_status=OrderStatus.objects.get(status='Принят'))
        order.order_info = "\n".join([item.product.brand + " " + str(item.count) for item in cart])
        order.save()
        for item in cart:
            item.order = order
            item.code = item.product.code
            item.brand = item.product.brand
            item.price_1 = item.product.price_with_currency
            item.price_2 = item.get_price_with_discount()
            item.supplier = item.product.supplier
            item.save()
    else:
        for item in cart:
            item.user = user
            item.code = item.product.code
            item.brand = item.product.brand
            item.price_1 = item.product.price_with_currency
            item.price_2 = item.get_price_with_discount()
            item.supplier = item.product.supplier
            item.save()
    cart.cart.checked_out = True
    cart.cart.save()
    cart.change_id(request)
    cart = Cart(request)
    request.basket_number = 0
    return HttpResponseRedirect("/basket")
开发者ID:Smiter,项目名称:voodoo,代码行数:31,代码来源:views.py

示例11: add_to_cart

def add_to_cart(request):
    print "add to cart\n"
    product = Product.objects.get(id=request.POST["product_id"])
    cart = Cart(request)
    cart.add(product)
    request.basket_number = cart.getItemCount()
    return render_to_response('basket.html',  dict(cart=cart, total_price=cart.getTotalPrice(), products=Product.objects.all()), context_instance=RequestContext(request))
开发者ID:Smiter,项目名称:voodoo,代码行数:7,代码来源:views.py

示例12: add_to_cart

def add_to_cart(request):    
    quantity = 1
    supply_id = request.GET.get('id', None)
    if (supply_id):

        user_id = "anon"
        if request.user.id:
            user_id = request.user.id


        supply = Supply.objects.get(id=supply_id)
        

        cart = Cart(request)
        cart.add(supply, supply.price, quantity)

        analytics.track(user_id, 'Added to cart', {
          'supply_id' : supply.id,
          "supply_name" : supply.name
        })
        
    if request.session.get('email', '') == '':
        return redirect('cart.views.get_email')

    return redirect('cart.views.view_cart')
开发者ID:kmax12,项目名称:lts,代码行数:25,代码来源:views.py

示例13: order_cart

def order_cart(request):
    if request.method == 'POST':
        form = OrderForm(request.POST)
        if form.is_valid():
            subject = u'Заказ с сайта'
            recipients = []
            try:
                recipients.extend(emails_list(request.settings.email))
            except:
                recipients.append(settings.ADMINS[0][1])
            cart = Cart(request, init=True)
            letter_context = form.cleaned_data
            letter_context.update({'site': request.settings.project})
            order_text = render_to_string('order_info.txt', {'cart': cart})
            letter_content = render_to_string('order_letter.txt', letter_context)
            letter_content += order_text
            send_mail(subject, letter_content, letter_context['email'] or recipients[0], recipients)
            success_message = u"""
            Благодарим за то, что Вы воспользовались услугами нашего Интернет-магазина.
            Ваша заявка принята в обработку и наш менеджер свяжется с Вами в ближайшее время для уточнения деталей.
            Мы будем благодарны Вам, если Вы оставите на нашем сайте свой отзыв о работе нашего  Интернет-магазина.
            """
            messages.add_message(request, messages.SUCCESS, success_message)
            cart.delete_all()
            return HttpResponseRedirect('')
    else:
        form = OrderForm()
    return render_to_response('cart_order.html', {'form': form},
        context_instance=RequestContext(request))   
开发者ID:Sergey-L,项目名称:v2,代码行数:29,代码来源:views.py

示例14: clear_cart

def clear_cart(request):
    if request.is_ajax():
        cart = Cart(request)
        cart.clear()
        return HttpResponse('cart was destroyed.')
    else:
        return HttpResponseRedirect('/')
开发者ID:aijogja,项目名称:Myton_Django_Project,代码行数:7,代码来源:views.py

示例15: cart

def cart(request):
    _cart = Cart(request)
    items = len(list(_cart.cart.item_set.all()))
    item_ct = get_model_content_type(Item)
    addon_ct = get_model_content_type(Addon)

    products = _cart.cart.item_set.filter(content_type=item_ct)
    addons = _cart.cart.item_set.filter(content_type=addon_ct)
    total_price = _cart.get_total_price()
    bonus_max = round(total_price * Decimal(str(0.1 / settings.DEFAULT_EXCHANGE_RATE)))
    service = None
    deliver_cost = None

    if products:
        # item could be deleted so careful
        try:
            service = products.all()[0].product.container.owner
            deliver_cost = service.get_deliver_cost(total_price)
        except ObjectDoesNotExist:
            _cart.cart.item_set.all().delete()
    context = {
        "cart": _cart,
        "kart": {
            "total_price": _cart.get_total_price(),
            "products": products,
            "cart_items": items or None,
            "addons": addons,
            "bonus_max": int(bonus_max),
            "service": service,
            "deliver_cost": int(deliver_cost) if deliver_cost is not None else None,
        },
    }

    return context
开发者ID:stden,项目名称:colortek,代码行数:34,代码来源:context_processors.py


注:本文中的cart.Cart类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。