【问题标题】:Adding product to cart - variable assignment django将产品添加到购物车 - 变量分配 django
【发布时间】:2019-12-18 14:32:55
【问题描述】:

我有将产品添加到购物车的功能。 但是,它不能正常工作。 首次将产品添加到购物车时,添加产品数量时始终添加 1。再次添加和添加价值后,一切正常。

product.html

        <div class="float-right">
        <form action="{% url 'cart:add_cart' product.id %}" method="post">
          {% csrf_token %}
          <div class="float-left">
          <input type="number" value="1" name="quantity" class="form-control" style="width: 100px">
        </div>
          <input class="btn send-click btn-md my-0 p" type="submit" value="Add to cart">
          </form> </div>

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:
        if request.method == 'POST':
          quantity = request.POST['quantity']
          cart_item.quantity += int(quantity)
      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')

quantity = 1 这一行有错误,我不知道要分配什么而不是这个 1。

编辑:

models.py

from django.db import models
from shop.models import Product

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

编辑:解决方案:

quantity = request.POST['quantity'],

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:
        if request.method == 'POST':
          quantity = request.POST['quantity']
          cart_item.quantity += int(quantity)
      cart_item.save()
    except CartItem.DoesNotExist:
      cart_item = CartItem.objects.create(
                  product = product,
                  quantity = request.POST['quantity'],
                  cart = cart
          )
      cart_item.save()
    return redirect('cart:cart_detail')

【问题讨论】:

  • 这通常是当CartItem 有一个必填字段(没有默认值)而您忘记传递给.create(..) 调用时。
  • 我不知道应该为数量分配什么以使其正常工作。
  • 请附上你得到的模型结构和错误详情
  • 我附加了 models.py 结构。这个错误是相当合乎逻辑的。第一次将产品添加到购物车时,您总是添加 1。尽管输入了不同的值。一旦这个产品在篮子里,我添加一个值,例如20,它有效。

标签: django python-3.x django-models django-templates django-views


【解决方案1】:

在此处添加force_update=True 参数cart_item.save(force_update=True)

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:
            if request.method == 'POST':
              quantity = request.POST['quantity']
              cart_item.quantity += int(quantity)
          # add argument force_update=True (because this query to update quantity field)
          cart_item.save(force_update=True)
        except CartItem.DoesNotExist:
          cart_item = CartItem.objects.create(
                      product = product,
                      quantity = 1,
                      cart = cart
              )
          cart_item.save()
        return redirect('cart:cart_detail')

你可以尝试这个代码来处理简单的异常,我希望这个逻辑能够成功。

def add_cart(request, product_id):
    if request.method == 'POST':
        product = Product.objects.get(id=product_id)

        cart, created = Cart.objects.get_or_create(cart_id=_cart_id(request))

        cart_item = CartItem.object.filter(product=product, cart=cart)
        if cart_item.exists():
            if cart_item.quantity < cart_item.product.stock:
                quantity = request.POST['quantity']
                cart_item.quantity += int(quantity)
                cart_item.save(force_update=True)
        else:
            CartItem.objects.create(
                product = product,
                quantity = 1,
                cart = cart
            )

    return redirect('cart:cart_detail')

【讨论】:

    猜你喜欢
    • 2012-06-09
    • 1970-01-01
    • 2011-12-19
    • 2014-11-21
    • 2014-12-17
    • 1970-01-01
    • 2016-02-28
    • 1970-01-01
    相关资源
    最近更新 更多