【问题标题】:How to calculate total price in django?如何计算django的总价?
【发布时间】:2022-01-05 15:32:33
【问题描述】:

我正在构建一个电子商务网站并尝试在 views.py 中计算产品的总价格,但我遇到了错误。

这是我的代码:

@login_required(login_url='/customer/login')
@customer()
def addtocart(request):
    if request.user.is_authenticated:
        buyer = request.user.is_customer
        cart = Cart.objects.filter(buyer = buyer)

        amount = 0.00
        cart_products = [p for p in Cart.objects.all() if p.buyer == buyer]

        if cart_products:
            for p in cart_products:
                t_amount = (p.products.discounted_price)
                total_amount += t_amount
    return render(request, 'Shop/cart.html', {'cart': cart, 'total_amount': total_amount})

这是它在浏览器中所说的:在赋值之前引用了局部变量“total_amount”
谢谢

【问题讨论】:

  • 这意味着您应该在for循环中进行累积和之前声明变量(即total_amount = 0)。

标签: django django-views


【解决方案1】:

您的可变金额 = 0.00 应重命名为 total_amount。

【讨论】:

  • 如果我这样做,总金额也会变为零
  • if 语句 'if cart_products:' 可能解析为 false,那么您的 total_amount 仍将返回 0.0。 'cart_products = [p for p in Cart.objects.all() if p.buyer == Buyer]' 或 if 语句被正确命中 't_amount = (p.products.discounted_price)' 可能有错误t_amount 可能返回零。
【解决方案2】:

当您没有任何cart_products 时,python 正在尝试读取变量 total_amount,但它超出了范围。在函数之上定义它。

def addtocart(request):
    total_amount = 0.00
    if request.user.is_authenticated:
        ....

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多