django - Django:如何在电子商务中获取总购物车项目
问题描述
我正在尝试添加购物车中的全部商品,但我不断收到
<0x000001CFFDED8228 处的属性对象>:
有人可以帮忙吗?
视图.py
class checkout(ListView):
model = OrderItem
template_name = 'product/checkout.html'
def get_context_data(self, **kwargs):
context = super(checkout, self).get_context_data(**kwargs)
context['orderQty'] = Order.get_cart_items
return context
模型.py
class Order(models.Model):
customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True)
date_ordered = models.DateTimeField(auto_now_add=True)
complete = models.BooleanField(default=False, null = True, blank=False)
transaction_id = models.CharField(max_length= 200, null=True)
def __str__(self):
return str(self.id)
@property
def get_cart_items(self):
orderitems = self.orderitem_set.all()
total = sum(item.quantity for item in orderitems)
return total
size_choices = (('small', 'S'),
('medium', 'M'),
('large', 'L'))
class OrderItem(models.Model):
product = models.ForeignKey(Product, on_delete=models.SET_NULL, blank=True, null=True)
order = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True, null=True)
date_added = models.DateTimeField(auto_now_add=True)
quantity = models.IntegerField(default=0, blank=True, null=True)
size = models.CharField(max_length= 200,choices= size_choices, default=0)
@property
def get_total(self):
total = self.product.price *self.quantity
return total
模板.html:
<div class="row-1">
<div style="flex:2;"><strong>Total Items</strong>:<span style="float: right;">{{orderQty}}</span></div>
<hr>
<div style="flex:2;"><strong>SubTotal</strong>:<span style="float: right;">$387</span></div>
<hr>
<div style="flex:2; margin-top:10px"><strong>Shipping</strong><span style="float: right;">$54</span></div>
<hr>
</div>
<div>
<div style="flex:2; text-align:center"><h6>Total: $387</h6></div>
<input id="form-button" class="btn btn-success btn-block" type="submit" value="Pay">
</div
我相信这些文件包含问题,但通过在线研究我似乎无法准确指出它是什么。我的网站的基于函数的视图运行良好,直到我转移到基于类的视图我的 views.py 文件。任何帮助将不胜感激。
解决方案
我相信问题出在这行代码上:
def get_context_data(self, **kwargs):
context = super(checkout, self).get_context_data(**kwargs)
context['orderQty'] = Order.get_cart_items # <----
return context
您只是在创建函数对象而不是调用它。将该行更改为此应该可以解决问题:
context['orderQty'] = Order.get_cart_items()
编辑当您定义时@property
,您的函数不再是函数对象,而是属性对象。由于property
是descriptor
和不可调用的,它会抛出该错误。有关更多信息,请查看此文档。因此,我建议您@property
在函数定义处删除以解决此问题。
推荐阅读
- sql - 必须声明标量变量“@FieldDataFileName_ID”
- ios - swiftui表单没有出现在列表中
- docker - 在 Docker 中通过 FFplay (FFmpeg) 播放流
- javascript - 如何将 React 组件渲染到另一个 Web 应用程序
- javascript - 设置选定的选项不起作用
- javascript - 仅基于 JavaScript 中的一个属性返回整个对象?
- python - 将存储在字典中的值添加为值列表
- vue.js - 在 vue jest 测试中模拟 axios 的自定义实例
- java - 返回具有父类类型的子时类型不匹配
- python - 用 dummy 覆盖所有类方法