如何将ID传递给项目

时间:2019-11-23 21:06:58

标签: python django

我的代码有问题。当我在购物车中添加两个具有相同url的商品时,我增加了第二个商品的数量,则仅增加了第一个商品,而不是购物车中的第二个商品。我认为在我的代码。 first()是问题。如何将每个项目的ID添加到代码中。我的代码如下。

enter image description here


class Item(models.Model):
    title = models.CharField(max_length=250)
    image = models.ImageField(null=True)
    price = models.IntegerField()
    old_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(max_length=250, unique=True)
    timestamp = models.DateTimeField(auto_now_add=True)
    active = models.BooleanField(default=True)

    class Meta:
        ordering = ['-timestamp']
        db_table = 'items'
        verbose_name_plural = 'Items'

    def __str__(self):
        return self.title

class OrderItem(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, 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}"

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 product(request, id):
    item = Item.objects.get(id=id)
    print(item)

    context = {
        'product': item,
    }
    return render(request,'product.html', context)

def add_to_cart(request, id):

    item = get_object_or_404(Item, id=id)

    item_var = [] #item variation
    if request.method == 'POST':
        print(request.POST)
        qty = request.POST['quantity']
        for items in request.POST:
            key = items
            val = request.POST[key]
            print(key,val)

            try:
                v = Variation.objects.get(
                    item=item,
                    category__iexact=key,
                    title__iexact=val
                )
                item_var.append(v)
            except:
                pass

    order_item_qs = OrderItem.objects.filter(
        item=item,
        user=request.user,
        ordered=False
    )
    print(order_item_qs)

    if len(item_var) > 0:
        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.first()
        order_item.quantity = qty
        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.quantity = qty
        order_item.save()
        order_item.id

        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.quantity = qty
                order.items.add(order_item)
                messages.info(request, "This item quantity was updated.")
                return redirect("shop: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("shop:order-summary")


def update_cart(request, id):
    item = get_object_or_404(Item, id=id)

    if request.method == 'POST':
        qty = request.POST['quantity']

    order_item_qs= OrderItem.objects.filter(
        item=item,
        user=request.user,
        ordered=False
    )

    if order_item_qs.exists():
        item = order_item_qs.first()
        item.quantity = qty
        item.save()

    return redirect("shop:order-summary")

Product Template:

    <form method="POST" action="{{ product.get_add_to_cart_url }}">
              {% csrf_token %}

           <p>
              <input type="button" value="-" class="minus">
              <input type="number" value="1" name="quantity" id="qty1" 
    class="quantity_class" min="1" required>
              <input type="button" value="+" class="plus">
          </p> 

              {% if product.variation_set.all %}

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

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

           {% endif %}

            <hr>

            <input class="btn btn-primary btn-md my-2 p" type="submit" 
    value="Add to cart">

            </form>

Order summary template:

    {% for order_item in object.items.all %}

    <form method="POST" action="{{ order_item.item.get_update_cart_url }}">
              {% csrf_token %}

            <p>
              <input type="button" value="-" class="minus">
              <input type="number" value="{{ order_item.quantity }}" 
    name="quantity" id="qty1" class="quantity_class" min="1" required>
              <input type="button" value="+" class="plus">
          </p>
              <input class="btn btn-primary btn-md my-2 p" type="submit" 
    value="Update cart">

            </form>
    {% endfor %}

0 个答案:

没有答案