Django-增加购物车中每种产品的数量

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Django-增加购物车中每种产品的数量相关的知识,希望对你有一定的参考价值。

我在购物车中添加了两种带有变化的产品,但我无法增加第二种产品的数量。当我单击第二个产品的数量“ +”号时,它会自动增加第一个产品的数量。为了解决这个问题,我已经有好几天的时间了,但是我失败了。谁来帮帮我! (很抱歉输入密码)。

型号:

class Item(models.Model):
    title = models.CharField(max_length=250)
    price = models.IntegerField()
    discount_price = models.IntegerField(null=True, blank=True)
    description = htmlField()
    category = models.CharField(choices=CATEGORY_CHOICES, max_length=2)
    label = models.CharField(choices=LABEL_CHOICES, max_length=1)
    slug = models.SlugField(unique=True,max_length=250)


    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse("product-detail", kwargs={
            'slug': self.slug
        })
    def get_add_to_cart_url(self):
        return reverse("add-to-cart", kwargs={
            'slug': self.slug
        })
    def get_remove_from_cart_url(self):
        return reverse("remove-from-cart", kwargs={
            'slug': self.slug
        })

class VariationManager(models.Manager):
    def all(self):
        return super(VariationManager, self).filter(active=True)

    def sizes(self):
        return self.all().filter(category='size')

    def colors(self):
        return self.all().filter(category='color')

VAR_CATEGORIES = (
    ('size', 'size'),
    ('color', 'color'),
    ('package', 'package'),
    )

class Variation(models.Model):
    item = models.ForeignKey(Item, on_delete=models.CASCADE)
    category = models.CharField(max_length=120, choices=VAR_CATEGORIES, default='size')
    title = models.CharField(max_length=120)
    active = models.BooleanField(default=True)

    objects = VariationManager()

    def __str__(self):
        return self.title   

    def get_add_to_cart_url(self):
        return reverse("add-to-cart", kwargs={
            'slug': self.slug
        })
    def get_remove_from_cart_url(self):
        return reverse("remove-from-cart", kwargs={
            'slug': self.slug
        })

class OrderItem(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    ordered = models.BooleanField(default=False)
    item = models.ForeignKey(Item, on_delete=models.CASCADE)
    quantity = models.IntegerField(default=1)
    variation = models.ManyToManyField(Variation)

    def __str__(self):
        return f"{self.quantity} of {self.item.title}"

    def get_total_item_price(self):
        return self.quantity * self.item.price

    def get_total_discount_item_price(self):
        return self.quantity * self.item.discount_price

    def get_amount_saved(self):
        return self.get_total_item_price() - self.get_total_discount_item_price()

    def get_final_price(self):
        if self.item.price:#self.item.discount_price:
            return self.get_total_item_price()#self.get_total_discount_item_price()
        #return self.get_total_item_price()

class Order(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    items = models.ManyToManyField(OrderItem)
    start_date = models.DateTimeField(auto_now_add=True)
    ordered_date = models.DateTimeField()
    ordered = models.BooleanField(default=False)

    def __str__(self):
        return self.user.username

    def get_total(self):
        total = 0
        for order_item in self.items.all():
            total += order_item.get_final_price()
        return total

VIEWS.PY:

def add_to_cart(request,slug):
    item = get_object_or_404(Item,slug=slug)
    order_item_qs = OrderItem.objects.filter(
        item=item,
        user=request.user,
        ordered=False
    )

    item_var = [] #item variation
    if request.method == 'POST':
        for items in request.POST:
            key = items
            val = request.POST[key]
            try:
                v = Variation.objects.get(
                    item=item,
                    category__iexact=key,
                    title__iexact=val
                )
                item_var.append(v)
            except:
                pass

        if len(item_var) > 0:
                #order_item_qs.variation.clear()
                for items in item_var:
                    order_item_qs = order_item_qs.filter(
                        variation__exact=items,
                    )


    if order_item_qs.exists():
        order_item = order_item_qs[0]
        # for order_item in order_item_qs:
         # order_item = order_item_qs.first()
        order_item.quantity += 1
        order_item.save()
        #print(order_item_qs)

    else:
        order_item = OrderItem.objects.create(
            item=item,
            user=request.user,
            ordered=False
        )
        order_item.variation.add(*item_var)
        order_item.save()


    order_qs = Order.objects.filter(user=request.user, ordered=False)
    if order_qs.exists():
        order = order_qs[0]
        #check if the order item is in the order
        if not order.items.filter(item__id=order_item.id).exists():
            order.items.add(order_item)
            messages.info(request, "This item quantity was updated.")
            return redirect("order-summary")
    else:
        ordered_date = timezone.now()
        order = Order.objects.create(user=request.user, ordered_date=ordered_date)
        order.items.add(order_item)
        messages.info(request, "This item was added to cart.")
        return redirect("order-summary")

模板(订单摘要):

<div class="quantity buttons_added">
    <a href="{% url 'remove-single-item-from-cart' order_item.item.slug %}"><input type="button" value="-" class="minus"></a>
        <input type="number" value="{{ order_item.quantity }}" title="Qty" class="input-text qty text" size="4" pattern="" inputmode="">
    <a href="{% url 'add-to-cart' order_item.item.slug %}">
        <input type="button" value="+" class="plus"></a>
    </div>

TEMPLATE (Product details):

<form class="form" method="POST" action="{{ items.get_add_to_cart_url }}">
              {% csrf_token %}
              <input class="btn btn-default btn-block" type="submit" value="Add to cart">

              {% if items.variation_set.all %}

              {% if items.variation_set.sizes %}
            <select class="form-control" name="size">
              {% for items in items.variation_set.sizes %}
              <option value="{{ items.title|lower }}">{{ items.title|capfirst }}</option>
              {% endfor %}                      
            </select>
           {% endif %}

           {% if items.variation_set.colors %}
            <select class="form-control" name="color">
              {% for items in items.variation_set.colors %}
              <option value="{{ items.title|lower }}">{{ items.title|capfirst }}</option>
              {% endfor %}                      
            </select>
           {% endif %}

           {% endif %}

            </form>
答案

您能告诉我打印结果(order_item_qs)

以上是关于Django-增加购物车中每种产品的数量的主要内容,如果未能解决你的问题,请参考以下文章

在 Shopify 中,如何通过 url 将不同数量的多个产品添加到购物车

如何使用 Flutter 中的 Provider 增加电子商务购物车中的商品数量

产品变体未反映 Django 电子商务项目中订单摘要中的更新数量

根据运输类别和商品数量添加 Woocommerce 费用

通过详细信息页面添加产品数量的问题

购物车前端开发