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


Python models.ProductVariation类代码示例

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


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

示例1: cart_item_view

def cart_item_view(request, template="shop/product.html", form_class=AddProductForm, extra_content=None, cart_id="", item_id=""):
    cart = Cart.objects.filter(id=cart_id).first()
    item = next(item for item in cart.items.iterator() if item.id == int(item_id))
    published_products = Product.objects.published(for_user=request.user)
    product = get_object_or_404(published_products, slug=item.url.split('/')[-1])
    fields = [f.name for f in ProductVariation.option_fields()]
    variations = product.variations.all()
    variations_json = dumps([dict([(f, getattr(v, f))
        for f in fields + ["sku", "image_id"]]) for v in variations])
    variation = ProductVariation.objects.filter(sku=item.sku).first()
    v_json = dict([(f, getattr(variation, f))
        for f in fields + ["sku", "image_id"] if getattr(variation, f) is not None])
    initial_data = dict(quantity=item.quantity, **v_json)
    initial_data['embroidery_type'] = item.personalization.embroidery_type
    initial_data['value'] = item.personalization.value
    
    add_product_form = form_class(request.POST or None, product=product,
                                  initial=initial_data, to_cart=False)
    context = {
        "product": product,
        "editable_obj": product,
        "images": product.images.all(),
        "variations": variations,
        "variations_json": variations_json,
        "has_available_variations": any([v.has_price() for v in variations]),
        "add_product_form": add_product_form,
        "item": item
    }
    return render(request, template, context)
开发者ID:tresbailey,项目名称:Carolina-Belle,代码行数:29,代码来源:views.py

示例2: product

def product(request, slug, template="shop/product.html"):
    """
    Display a product - convert the product variations to JSON as well as 
    handling adding the product to either the cart or the wishlist.
    """
    published_products = Product.objects.published(for_user=request.user)
    product = get_object_or_404(published_products, slug=slug)
    AddProductForm = get_add_product_form(product)
    add_product_form = AddProductForm(initial={"quantity": 1})
    if request.method == "POST":
        to_cart = request.POST.get("add_wishlist") is None
        add_product_form = AddProductForm(request.POST, to_cart=to_cart)
        if add_product_form.is_valid():
            if to_cart:
                Cart.objects.from_request(request).add_item(
                    add_product_form.variation, 
                    add_product_form.cleaned_data["quantity"])
                info(request, _("Item added to cart"), fail_silently=True)
                return HttpResponseRedirect(reverse("shop_cart"))
            else:
                skus = request.COOKIES.get("wishlist", "").split(",")
                sku = add_product_form.variation.sku
                if sku not in skus:
                    skus.append(sku)
                info(request, _("Item added to wishlist"), fail_silently=True)
                response = HttpResponseRedirect(reverse("shop_wishlist"))
                set_cookie(response, "wishlist", ",".join(skus))
                return response
    variations = product.variations.all()
    variations_json = simplejson.dumps([dict([(f, getattr(v, f)) for f in 
        ["sku", "image_id"] + [f.name for f in ProductVariation.option_fields()]]) 
        for v in variations])
    return render_to_response(template, {"product": product, "variations_json":
        variations_json, "variations": variations, "images": product.images.all(),
        "add_product_form": add_product_form}, RequestContext(request))
开发者ID:alyoung,项目名称:cartridge,代码行数:35,代码来源:views.py

示例3: variations_json

def variations_json(variations):
    """
    Gets variations including the num_in_stock attribute into json format.
    """
    fields = [field.name for field in ProductVariation.option_fields()]
    variations_json = dumps([dict([(field, str(getattr(variation, field))) if isinstance(getattr(variation, field), Decimal) else (field, getattr(variation, field))
        for field in fields + ["sku", "image_id", "num_in_stock"]]) for variation in variations])
    return variations_json
开发者ID:jpells,项目名称:madeinboston,代码行数:8,代码来源:quantity_option_updater.py

示例4: product

def product(request, slug, template="shop/product.html",
            form_class=AddProductForm, extra_context=None):
    """
    Display a product - convert the product variations to JSON as well as
    handling adding the product to either the cart or the wishlist.
    """
    published_products = Product.objects.published(for_user=request.user)
    product = get_object_or_404(published_products, slug=slug)
    fields = [f.name for f in ProductVariation.option_fields()]
    variations = product.variations.all()
    variations_json = dumps([dict([(f, getattr(v, f))
        for f in fields + ["sku", "image_id"]]) for v in variations])
    to_cart = (request.method == "POST" and
               request.POST.get("add_wishlist") is None)
    initial_data = {}
    if variations:
        initial_data = dict([(f, getattr(variations[0], f)) for f in fields])
    initial_data["quantity"] = 1
    add_product_form = form_class(request.POST or None, product=product,
                                  initial=initial_data, to_cart=to_cart)
    if request.method == "POST":
        if add_product_form.is_valid():
            if to_cart:
                quantity = add_product_form.cleaned_data["quantity"]
                request.cart.add_item(add_product_form.variation, quantity)
                recalculate_cart(request)
                info(request, _("Item added to cart"))
                return redirect("shop_cart")
            else:
                skus = request.wishlist
                sku = add_product_form.variation.sku
                if sku not in skus:
                    skus.append(sku)
                info(request, _("Item added to wishlist"))
                response = redirect("shop_wishlist")
                set_cookie(response, "wishlist", ",".join(skus))
                return response
    related = []
    if settings.SHOP_USE_RELATED_PRODUCTS:
        related = product.related_products.published(for_user=request.user)
    context = {
        "product": product,
        "editable_obj": product,
        "images": product.images.all(),
        "variations": variations,
        "variations_json": variations_json,
        "has_available_variations": any([v.has_price() for v in variations]),
        "related_products": related,
        "add_product_form": add_product_form
    }
    context.update(extra_context or {})

    templates = [u"shop/%s.html" % str(product.slug), template]
    # Check for a template matching the page's content model.
    if getattr(product, 'content_model', None) is not None:
        templates.insert(0, u"shop/products/%s.html" % product.content_model)

    return TemplateResponse(request, templates, context)
开发者ID:raushanraj,项目名称:cartridge,代码行数:58,代码来源:views.py

示例5: _add_to_cart

 def _add_to_cart(self, variation, quantity):
     """
     Given a variation, creates the dict for posting to the cart
     form to add the variation, and posts it.
     """
     field_names = [f.name for f in ProductVariation.option_fields()]
     data = dict(list(zip(field_names, variation.options())))
     data["quantity"] = quantity
     self.client.post(variation.product.get_absolute_url(), data)
开发者ID:ArturFis,项目名称:cartridge,代码行数:9,代码来源:tests.py

示例6: test_cart

    def test_cart(self):
        """
        Test the cart object and cart add/remove forms.
        """
        self._product.variations.all().delete()
        self._product.variations.create_from_options(self._options)
        variation = self._product.variations.all()[0]
        variation.unit_price = TEST_PRICE
        variation.num_in_stock = TEST_STOCK * 2
        variation.save()

        # Test initial cart.
        cart = Cart.objects.from_request(self.client)
        self.assertFalse(cart.has_items())
        self.assertEqual(cart.total_quantity(), 0)
        self.assertEqual(cart.total_price(), Decimal("0"))


        # Add quantity and check stock levels / cart totals.
        field_names = [f.name for f in ProductVariation.option_fields()]
        data = dict(zip(field_names, variation.options()))
        data["quantity"] = TEST_STOCK
        self.client.post(self._product.get_absolute_url(), data)
        cart = Cart.objects.from_request(self.client)
        variation = self._product.variations.all()[0]
        self.assertTrue(variation.has_stock(TEST_STOCK))
        self.assertFalse(variation.has_stock(TEST_STOCK * 2))
        self.assertTrue(cart.has_items())
        self.assertEqual(cart.total_quantity(), TEST_STOCK)
        self.assertEqual(cart.total_price(), TEST_PRICE * TEST_STOCK)

        # Add remaining quantity and check again.
        self.client.post(self._product.get_absolute_url(), data)
        cart = Cart.objects.from_request(self.client)
        variation = self._product.variations.all()[0]
        self.assertFalse(variation.has_stock())
        self.assertTrue(cart.has_items())
        self.assertEqual(cart.total_quantity(), TEST_STOCK * 2)
        self.assertEqual(cart.total_price(), TEST_PRICE * TEST_STOCK * 2)

        # Remove from cart.
        data = {"items-INITIAL_FORMS": 0, "items-TOTAL_FORMS": 0,
                "update_cart": 1}
        for i, item in enumerate(cart):
            data["items-INITIAL_FORMS"] += 1
            data["items-TOTAL_FORMS"] += 1
            data["items-%s-id" % i] = item.id
            data["items-%s-DELETE" % i] = "on"
        self.client.post(reverse("shop_cart"), data)
        cart = Cart.objects.from_request(self.client)
        variation = self._product.variations.all()[0]
        self.assertTrue(variation.has_stock(TEST_STOCK * 2))
        self.assertFalse(cart.has_items())
        self.assertEqual(cart.total_quantity(), 0)
        self.assertEqual(cart.total_price(), Decimal("0"))
开发者ID:BeUnique,项目名称:cartridge,代码行数:55,代码来源:tests.py

示例7: test_cart

    def test_cart(self):
        """
        Test the cart object and cart add/remove forms.
        """
        product_options = ProductOption.objects.as_fields()
        self._product.variations.all().delete()
        self._product.variations.create_from_options(product_options)
        price = Decimal("20")
        num_in_stock = 5
        variation = self._product.variations.all()[0]
        variation.unit_price = price
        variation.num_in_stock = num_in_stock * 2
        variation.save()

        # Test initial cart.
        cart = Cart.objects.from_request(self.client)
        self.assertFalse(cart.has_items())
        self.assertEqual(cart.total_quantity(), 0)
        self.assertEqual(cart.total_price(), Decimal("0"))

        # Add quantity and check stock levels / cart totals.
        data = dict(zip([field.name for field in 
            ProductVariation.option_fields()], variation.options()))
        data["quantity"] = num_in_stock
        self.client.post(self._product.get_absolute_url(), data)
        cart = Cart.objects.from_request(self.client)
        variation = self._product.variations.all()[0]
        self.assertTrue(variation.has_stock(num_in_stock))
        self.assertFalse(variation.has_stock(num_in_stock * 2))
        self.assertTrue(cart.has_items())
        self.assertEqual(cart.total_quantity(), num_in_stock)
        self.assertEqual(cart.total_price(), price * num_in_stock)

        # Add remaining quantity and check again.
        self.client.post(self._product.get_absolute_url(), data)
        cart = Cart.objects.from_request(self.client)
        variation = self._product.variations.all()[0]
        self.assertFalse(variation.has_stock())
        self.assertTrue(cart.has_items())
        self.assertEqual(cart.total_quantity(), num_in_stock * 2)
        self.assertEqual(cart.total_price(), price * num_in_stock * 2)

        # Remove from cart.
        for item in cart:
            self.client.post(reverse("shop_cart"), {"item_id": item.id})
        cart = Cart.objects.from_request(self.client)
        variation = self._product.variations.all()[0]
        self.assertTrue(variation.has_stock(num_in_stock * 2))
        self.assertFalse(cart.has_items())
        self.assertEqual(cart.total_quantity(), 0)
        self.assertEqual(cart.total_price(), Decimal("0"))
开发者ID:alyoung,项目名称:cartridge,代码行数:51,代码来源:tests.py

示例8: product

def product(request, slug, template="shop/product.html"):
    """
    Display a product - convert the product variations to JSON as well as
    handling adding the product to either the cart or the wishlist.
    """
    published_products = Product.objects.published(for_user=request.user)
    product = get_object_or_404(published_products, slug=slug)
    fields = [f.name for f in ProductVariation.option_fields()]
    variations = product.variations.all()
    variations_json = simplejson.dumps([dict([(f, getattr(v, f))
                                        for f in fields + ["sku", "image_id"]])
                                        for v in variations])
    to_cart = (request.method == "POST" and
               request.POST.get("add_wishlist") is None)
    initial_data = {}
    if variations:
        initial_data = dict([(f, getattr(variations[0], f)) for f in fields])
    initial_data["quantity"] = 1
    add_product_form = AddProductForm(request.POST or None, product=product,
                                      initial=initial_data, to_cart=to_cart)
    if request.method == "POST":
        if add_product_form.is_valid():
            if to_cart:
                quantity = add_product_form.cleaned_data["quantity"]
                request.cart.add_item(add_product_form.variation, quantity)
                recalculate_discount(request)
                recalculate_billship_tax(request)
                info(request, _("Item added to cart"))
                return redirect("shop_cart")
            else:
                skus = request.wishlist
                sku = add_product_form.variation.sku
                if sku not in skus:
                    skus.append(sku)
                info(request, _("Item added to wishlist"))
                response = redirect("shop_wishlist")
                set_cookie(response, "wishlist", ",".join(skus))
                return response
    context = {
        "product": product,
        "editable_obj": product,
        "images": product.images.all(),
        "variations": variations,
        "variations_json": variations_json,
        "has_available_variations": any([v.has_price() for v in variations]),
        "related_products": product.related_products.published(
                                                      for_user=request.user),
        "add_product_form": add_product_form
    }
    templates = [u"shop/%s.html" % unicode(product.slug), template]
    return render(request, templates, context)
开发者ID:jbmckeon,项目名称:cartridge,代码行数:51,代码来源:views.py.BASE.7588.py

示例9: __init__

    def __init__(self, *args, **kwargs):
        """
        Handles adding a variation to the cart or wishlist.

        When adding from the product page, the product is provided
        from the view and a set of choice fields for all the
        product options for this product's variations are added to
        the form. When the form is validated, the selected options
        are used to determine the chosen variation.

        A ``to_cart`` boolean keyword arg is also given specifying
        whether the product is being added to a cart or wishlist.
        If a product is being added to the cart, then its stock
        level is also validated.

        When adding to the cart from the wishlist page, a sku is
        given for the variation, so the creation of choice fields
        is skipped.
        """
        self._product = kwargs.pop("product", None)
        self._to_cart = kwargs.pop("to_cart")
        super(AddProductForm, self).__init__(*args, **kwargs)
        # Adding from the wishlist with a sku, bail out.
        if args[0] is not None and args[0].get("sku", None):
            return
        # Adding from the product page, remove the sku field
        # and build the choice fields for the variations.
        del self.fields["sku"]
        option_fields = ProductVariation.option_fields()
        if not option_fields:
            return
        option_names, option_labels = list(zip(*[(f.name, f.verbose_name)
            for f in option_fields]))
        option_values = list(zip(*self._product.variations.filter(
            unit_price__isnull=False).values_list(*option_names)))
        if option_values:
            for i, name in enumerate(option_names):
                values = [_f for _f in set(option_values[i]) if _f]
                if values:
                    field = forms.ChoiceField(label=option_labels[i],
                                              choices=make_choices(values))
                    self.fields[name] = field
        if self._product.content_model == 'reservableproduct':
            # ReservableProduct needs from/to dates and does not need quantity
            self.fields["from_date"] = forms.DateField(input_formats=["%d.%m.%Y"], widget=forms.HiddenInput())
            self.fields["to_date"] = forms.DateField(input_formats=["%d.%m.%Y"], widget=forms.HiddenInput())
            self.fields["quantity"] = forms.IntegerField(min_value=1, initial=1, widget=forms.HiddenInput())
开发者ID:jaywink,项目名称:cartridge-reservable,代码行数:47,代码来源:forms.py

示例10: __init__

    def __init__(self, *args, **kwargs):
        """
        Handles adding a variation to the cart or wishlist.

        When adding from the product page, the product is provided
        from the view and a set of choice fields for all the
        product options for this product's variations are added to
        the form. When the form is validated, the selected options
        are used to determine the chosen variation.

        A ``to_cart`` boolean keyword arg is also given specifying
        whether the product is being added to a cart or wishlist.
        If a product is being added to the cart, then its stock
        level is also validated.

        When adding to the cart from the wishlist page, a sku is
        given for the variation, so the creation of choice fields
        is skipped.
        """
        self._product = kwargs.pop("product", None)
        self._to_cart = kwargs.pop("to_cart")
        super(AddProductForm, self).__init__(*args, **kwargs)
        # Adding from the wishlist with a sku, bail out.
        if args[0] is not None and args[0].get("sku", None):
            return
        # Adding from the product page, remove the sku field
        # and build the choice fields for the variations.
        del self.fields["sku"]
        option_fields = ProductVariation.option_fields()
        if not option_fields:
            return
        option_names, option_labels = zip(*[(f.name, f.verbose_name)
            for f in option_fields])
        option_values = zip(*self._product.variations.filter(
            unit_price__isnull=False).values_list(*option_names))
        if option_values:
            for i, name in enumerate(option_names):
                values = list(option_values[i])
                try:
                    values.remove(None)
                except ValueError:
                    pass
                if values:
                    field = forms.ChoiceField(label=option_labels[i],
                                              choices=make_choices(values))
                    self.fields[name] = field
开发者ID:SethBoyd,项目名称:cartridge,代码行数:46,代码来源:forms.py

示例11: __init__

 def __init__(self, *args, **kwargs):
     """
     Create each ChoiceField for selecting from the product's variations.
     """
     self._to_cart = kwargs.pop("to_cart", True)
     super(AddProductForm, self).__init__(*args, **kwargs)
     option_names, option_labels = zip(*[(f.name, f.verbose_name) 
         for f in ProductVariation.option_fields()])
     option_values = zip(*product.variations.filter(
         unit_price__isnull=False).values_list(*option_names))
     if option_values:
         for i, name in enumerate(option_names):
             values = filter(None, set(option_values[i]))
             if values:
                 field = forms.ChoiceField(label=option_labels[i], 
                     choices=make_choices(values))
                 self.fields[name] = field
开发者ID:alyoung,项目名称:cartridge,代码行数:17,代码来源:forms.py

示例12: product

def product(request, prod, template="shop/product.html",
            form_class=AddProductForm):
    #pdb.set_trace()
    fields = [f.name for f in ProductVariation.option_fields()]
    variations = prod.variations.all()
    variations_json = dumps([dict([(f, getattr(v, f))
        for f in fields + ["sku", "image_id"]]) for v in variations])
    to_cart = (request.method == "POST" and
               request.POST.get("add_wishlist") is None)
    initial_data = {}
    initial_data["quantity"] = 1
    add_product_form = form_class(request.POST or None, product=prod,
                                  initial=initial_data, to_cart=to_cart)
        
    context = {
        "variations": variations,
        "add_product_form": add_product_form
    }

    return context
开发者ID:davit-gh,项目名称:flaunt,代码行数:20,代码来源:views.py

示例13: parse_description

def parse_description(value, autoescape=True):
    """
    Split product description to title and options to allow different styling.
    Returns html with title and options in two lines with different classes:
    'title' and 'options'.
    """
    option_fields = ProductVariation.option_fields()
    if option_fields:
        first_option_label = option_fields[0].verbose_name
        m = re.match(ur"(.*\w*)\s(%s.*)$" % first_option_label, value, re.I | re.U)
    if m:
        title = m.group(1)
        options = m.group(2)
        if autoescape:
            esc = conditional_escape
        else:
            esc = lambda x: x
        return mark_safe(
            "<span class='title'>%s</span><br><span class='options'>%s</span>" % (esc(title), esc(options)))
    else:
        return value
开发者ID:henri-hulski,项目名称:cartridge_offcanvas,代码行数:21,代码来源:offcanvas_shop_tags.py

示例14: product

def product(request, slug, template="shop/product.html"):
    """
    Display a product - convert the product variations to JSON as well as
    handling adding the product to either the cart or the wishlist.
    """
    published_products = Product.objects.published(for_user=request.user)
    product = get_object_or_404(published_products, slug=slug)
    to_cart = request.method == "POST" and request.POST.get("add_wishlist") is None
    add_product_form = AddProductForm(request.POST or None, product=product, initial={"quantity": 1}, to_cart=to_cart)
    if request.method == "POST":
        if add_product_form.is_valid():
            if to_cart:
                quantity = add_product_form.cleaned_data["quantity"]
                request.cart.add_item(add_product_form.variation, quantity)
                recalculate_discount(request)
                info(request, _("Item added to cart"))
                return HttpResponseRedirect(reverse("shop_cart"))
            else:
                skus = request.wishlist
                sku = add_product_form.variation.sku
                if sku not in skus:
                    skus.append(sku)
                info(request, _("Item added to wishlist"))
                response = HttpResponseRedirect(reverse("shop_wishlist"))
                set_cookie(response, "wishlist", ",".join(skus))
                return response
    fields = [f.name for f in ProductVariation.option_fields()]
    fields += ["sku", "image_id"]
    variations = product.variations.all()
    variations_json = simplejson.dumps([dict([(f, getattr(v, f)) for f in fields]) for v in variations])
    context = {
        "product": product,
        "images": product.images.all(),
        "variations": variations,
        "variations_json": variations_json,
        "has_available_variations": any([v.has_price() for v in variations]),
        "related": product.related_products.published(for_user=request.user),
        "add_product_form": add_product_form,
    }
    return render_to_response(template, context, RequestContext(request))
开发者ID:pombredanne,项目名称:cartridge,代码行数:40,代码来源:views.py

示例15: test_order

    def test_order(self):
        """
        Test that a completed order contains cart items and that
        they're removed from stock.
        """

        # Get a variation.
        self._product.variations.all().delete()
        self._product.variations.create_from_options(self._options)
        variation = self._product.variations.all()[0]
        variation.unit_price = TEST_PRICE
        variation.num_in_stock = TEST_STOCK * 2
        variation.save()

        # Add to cart.
        field_names = [f.name for f in ProductVariation.option_fields()]
        data = dict(zip(field_names, variation.options()))
        data["quantity"] = TEST_STOCK
        self.client.post(self._product.get_absolute_url(), data)
        cart = Cart.objects.from_request(self.client)

        # Post order.
        data = {"step": len(CHECKOUT_STEPS)}
        self.client.post(reverse("shop_checkout"), data)
        try:
            order = Order.objects.from_request(self.client)
        except Order.DoesNotExist:
            self.fail("Couldn't create an order")
        items = order.items.all()
        variation = self._product.variations.all()[0]

        self.assertEqual(cart.total_quantity(), 0)
        self.assertEqual(len(items), 1)
        self.assertEqual(items[0].sku, variation.sku)
        self.assertEqual(items[0].quantity, TEST_STOCK)
        self.assertEqual(variation.num_in_stock, TEST_STOCK)
        self.assertEqual(order.item_total, TEST_PRICE * TEST_STOCK)
开发者ID:BeUnique,项目名称:cartridge,代码行数:37,代码来源:tests.py


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