开发者社区> 问答> 正文

在django中将特定数量的产品添加到购物车

我有一个问题,因为我不知道如何实现“添加特定数量的产品到购物车”。 目前,在按下“加入购物车”按钮后,只会增加一个产品数量。 我不知道如何在视图和模板中联系起来。 我希望它取给定的值而不是1。

cart_item.quantity += 1

车/ views.py

def add_cart(request, product_id):
    product = Product.objects.get(id=product_id)
    try:
        cart = Cart.objects.get(cart_id=_cart_id(request))
    except Cart.DoesNotExist:
        cart = Cart.objects.create(
                cart_id = _cart_id(request)
            )
        cart.save()
    try:
      cart_item = CartItem.objects.get(product=product, cart=cart)
      if cart_item.quantity < cart_item.product.stock:
          cart_item.quantity += 1
      cart_item.save()
    except CartItem.DoesNotExist:
      cart_item = CartItem.objects.create(
                  product = product,
                  quantity = 1,
                  cart = cart
          )
      cart_item.save()
    return redirect('cart:cart_detail')

车/ models.py

class Cart(models.Model):
    cart_id = models.CharField(max_length=250, blank=True)
    date_added = models.DateField(auto_now_add=True)
    class Meta:
        db_table = 'Cart'
        ordering = ['date_added']

    def __str__(self):
        return self.cart_id

class CartItem(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    cart = models.ForeignKey(Cart, on_delete=models.CASCADE)
    quantity = models.IntegerField()
    active = models.BooleanField(default=True)
    class Meta:
        db_table = 'CartItem'

    def sub_total(self):
        return self.product.price * self.quantity

    def __str__(self):
        return self.product

模板/商店/ product.html

  <div class="float-right">
   <div class="float-left"> <input type="number" value="1" aria-label="Search" 
    class="form-control" style="width: 100px"> </div>
    <a class="btn send-click btn-md my-0 p"  href="{% url 'cart:add_cart' product.id %}">Add to Cart</a></div>

urls . py

app_name='cart'

urlpatterns = [
    path('add/<int:product_id>/', views.add_cart, name='add_cart'),
    path('', views.cart_detail, name='cart_detail'),
    path('remove/<int:product_id>/', views.cart_remove, name='cart_remove'),
    path('full_remove/<int:product_id>/', views.full_remove, name='full_remove'),
]

问题来源StackOverflow 地址:/questions/59379019/adding-a-specific-quantity-of-the-product-to-the-cart-in-django

展开
收起
kun坤 2019-12-30 09:55:15 530 0
1 条回答
写回答
取消 提交回答
  • 如果你不想用post处理的形式,你可以用inline JS获取金额。您需要调整您的url和视图来接受项目的数量。

    <div class="float-right">
       <div class="float-left"> <input id="amount_field" type="number" value="1" aria-label="Search" 
        class="form-control" style="width: 100px"> </div>
        <button type="button" onclick="location.href='{% url \"cart:add_cart\" product.id %}'.concat("/",document.getElementById('amount_field').value);" >Add Items</button>
    </div>
    
    2019-12-30 09:55:22
    赞同 展开评论 打赏
问答分类:
问答标签:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载