I'm building an ecommerce website and trying to calculate the total price of the products in views.py but I'm getting an error.
Here is my code:
@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})
This is what it says in the browser: local variable 'total_amount' referenced before assignment.
Thank you
CodePudding user response:
Your Variable amount = 0.00 should be renamed to total_amount.
CodePudding user response:
When you don't have any cart_products, python is trying to read the variable total_amount, but it is out of scope. Define it on top of the function.
def addtocart(request):
total_amount = 0.00
if request.user.is_authenticated:
....
