“Medicine”对象没有属性“add”错误

2024-10-08 16:45:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从药物列表中将药物添加到我的购物车中。我创建了一个视图,但单击“添加”按钮时出现以下错误:

AttributeError at /cart/3/ 'Medicine' object has no attribute 'add'

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

carts/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")

手推车/模型.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格式的plus按钮**

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

Tags: addidtrueautomodels按钮nowclass
1条回答
网友
1楼 · 发布于 2024-10-08 16:45:36

购物车到产品具有^{}关系。所以add在这里不起作用。您需要像这样更新代码:

cart.product = medicine
cart.save()

或者你可以把它做成^{}关系。例如:

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

相关问题 更多 >

    热门问题