首页 > 解决方案 > 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 文件。任何帮助将不胜感激。

标签: djangodjango-modelsdjango-viewsdjango-formsdjango-templates

解决方案


我相信问题出在这行代码上:

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,您的函数不再是函数对象,而是属性对象。由于propertydescriptor和不可调用的,它会抛出该错误。有关更多信息,请查看此文档。因此,我建议您@property在函数定义处删除以解决此问题。


推荐阅读