[英]Adding a specific quantity of the product to the cart in 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>
網址.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'),
]
如果您不想更改為具有后期處理功能的表單,您可以使用內聯 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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.