python - '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>
解决方案
购物车与产品有OneToOne
关系。所以add
不会在这里工作。您需要像这样更新代码:
cart.product = medicine
cart.save()
或者你可以把它ManyToMany
联系起来。例如:
class Cart(models.Model):
# rest of the code
product = models.ManyToMany(Medicine)
# rest of the code
推荐阅读
- java - Elastic Transcoder 输出持续时间与我的输入持续时间的总和不匹配
- python - 连接两个数据框并扩展其中一个的内容
- css - CSS 如何连接线
- c# - Unity - scale UI element based on closeness to a target?
- r - 根据每行中的缺失值选择列
- python - Why is etree returning nothing from my SVG when I run `for glyph in font.iter('glyph')`?
- angular-material - 角材料单选按钮组 - 屏幕阅读器无法正确阅读
- python - Google EdgeTPU 无法让 PWM 与 Python 一起使用
- c - 从文件中填充结构数组
- java - Null point error in Array when trying to give Buttons in array a color