Django Cart Total

Viewed 19

I am making an e-commerce site with django. I set it to pay with paypal. But my problem is that I can't set the cart total when you pay.

Here is the html code:

...
createOrder: function(data, actions) {
                return actions.order.create({
                    purchase_units: [{
                        amount: {
                            value:'{{value}}'
                        }
                    }]
                });
            },
...

Here is the models.py

class Product(models.Model):
    name = models.CharField(max_length=200)
    image = models.ImageField(upload_to='images/')
    value = models.IntegerField(null=True)
    def __str__(self):
        return self.name

class Order(models.Model):
    username = models.CharField(max_length=200,null=True)
    name = models.CharField(max_length=200)
    value = models.IntegerField(null=True)
    image = models.ImageField(upload_to='images1/',null=True)
    def __str__(self):
        return self.name

Here is the views.py:

#Make an order
if request.method == 'POST':
    name = request.POST['name']
    product = Product.objects.filter(name=name).first()
    value = int(product.value)
    order = Order(name=name,username=cookie,value=value,image=product.image)
    order.save()

#Buy
def buy(request):
    cookie = request.COOKIES.get('name')
    if not cookie:
        return redirect('/')
    orders = Order.objects.filter(username=cookie).all()
    for i in orders:
        global value
        value = int(i.value)
        value = value + value
    return render(request,'cart.html',{'orders':orders,'value':value})

But I don't get the right value. How can I count the total value?

Thanks.

1 Answers

Is there a reason why you are looping over the orders to calculate the total value? If not, you can use Django Aggregation instead. You can use the following lines of code to calculate the total value of all orders:

from django.db.models import Sum

def buy(request):
    cookie = request.COOKIES.get('name')
    if not cookie:
        return redirect('/')
    orders = Order.objects.filter(username=cookie).all()
    value = orders.aggregate(Sum('value'))['value__sum']
    return render(request,'cart.html',{'orders':orders,'value':value})
Related