首页 > 解决方案 > 'Medicine' 对象没有属性 'add' 错误

问题描述

我想从药物清单中将药物添加到我的购物车。我创建了一个视图,但是当我单击添加按钮时,它给出了这个错误:

/cart/3/ 'Medicine' 对象的 AttributeError 没有属性 'add'

我希望当用户单击+按钮时,药物将被添加到用户购物车中。我可以从管理面板添加它,但不能从网页添加。这是我的代码。请帮我。

购物车/views.py

def update_cart(request, id):
    current_user = request.user
    cart = Cart.objects.filter().first()

    try:
        medicine = Medicine.objects.get(id=id)
    except Medicine.DoesNotExist:
        pass
    except:
        pass
    cart.product.add(medicine)
    return HttpResponseRedirect("/cart")

购物车/models.py

class Cart(models.Model):

    user = models.TextField(User)
    product = models.OneToOneField(Medicine, on_delete=models.CASCADE, primary_key=True)
    total = models.DecimalField(max_digits=100, decimal_places=2, default=0.00)
    timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
    updated = models.DateTimeField(auto_now_add=False, auto_now=True)
    active = models.BooleanField(default=True)

**html中的加号按钮**

<a href="/cart/{{medicine.id}}" class="btn btn-sq-xs btn-success">
              <i class="fa fa-plus fa-1x"></i><br/>
            </a>

标签: pythondjango

解决方案


购物车与产品有OneToOne关系。所以add不会在这里工作。您需要像这样更新代码:

cart.product = medicine
cart.save()

或者你可以把它ManyToMany联系起来。例如:

class Cart(models.Model):
    # rest of the code
    product = models.ManyToMany(Medicine)
    # rest of the code

推荐阅读