You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django购物车功能报错:重复添加返回None及Admin类型错误

Django购物车功能两个错误的修复方案

错误1:ValueError: The view didn't return an HttpResponse object

问题原因

add_cart视图中,仅在首次创建CartItem(触发CartItem.DoesNotExist异常分支)时返回了redirect响应;当再次添加同一商品(进入更新已有CartItem的try分支)时,无任何返回语句,导致视图返回None,触发Django的ValueError。

修复代码

调整add_cart视图的返回逻辑,将return redirect移到try-except块外部,确保无论创建还是更新CartItem,视图都能返回HttpResponse对象:

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)
        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('carts:cart-view')

错误2:TypeError: __str__ returned non-string (type Product)

问题原因

CartItem模型的__str__方法直接返回了self.product(Product对象),而Django要求__str__必须返回字符串类型。尽管Product模型自身的__str__返回字符串,但直接返回对象会导致类型不匹配。

修复代码

修改CartItem的__str__方法,返回Product对象的字符串表示(或直接返回商品名称):

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

    def __str__(self):
        # 方案1:利用Product的__str__方法转成字符串
        return str(self.product)
        # 方案2:直接返回商品名称(更明确)
        # return self.product.product_name

内容的提问来源于stack exchange,提问作者Kirill Meha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 15:30:53