I am using to sum all the expense values which are assigned to an user. I am not able to display it in my webpage. How can i do that? The models.py code is as follows:
class expense(models.Model):
Expensecat=(('food','Food'),
('transportation','Transportation'),
('education','Education'),
('health','Health'),
('clothes','Clothes'),
('beauty','Beauty'),
('hosuehold','Household'),
)
ExpenseAmount=models.FloatField(max_length=100)
Category=models.CharField(max_length=200,choices= Expensecat)
Description=models.TextField(max_length=200)
Date=models.DateTimeField(default=timezone.now)
user=models.ForeignKey(User,on_delete=models.CASCADE)
Views.py
def home(request):
try:
expense_total = expense.objects.filter(user=request.user).aggregate(expenses=Sum('ExpenseAmount'))
except TypeError:
print('No data')
data = {
'Expense':expense_total['expenses'],
}
return render(request, 'budget/home.html', data )
HTML CODE:
<div class="col-lg-3 col-md-6 d-flex stat my-3">
<div class="mx-auto">
<h6 class="text-muted">Expense</h6>
<h3 class="font-weight-bold">{{ Expense.expenses }}</h3>
<h6 class="text-success"></h6>
</div>
You assign this to the Expense
variable, so you render this with Expense
, so not Expense.expenses
, you already "unwrapped" the value from the dictionary:
{{ }}
Note : When you make calculations with money, it is better to use a
DecimalField
[Django-doc] , not aFloatField
[Django-doc] . Floats can generate rounding errors when you perform calculations. You can also usedjango-money
[GitHub] to specify aMoneyField
. This has also specifies a currency, and can convert money to a different currency.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.