我正在构建一个贷款系统来计算还款期限。当我运行代码时遇到这个问题,它只显示最后一行。下面是我的观点.py 请我需要它来显示所有行,而不仅仅是最后一行
def sveloan(request):
if 'userid' in request.session:
if request.method == 'POST':
balance = 120000
annual_interest_rate = 42
monthly_payment_rate =0.3
monthly_interest_rate = annual_interest_rate / 12
monthly_payment = monthly_payment_rate * balance
new_balance= (balance - monthly_payment) * (1 + monthly_interest_rate)
for month in range(1, 6):
monthly_payment = 20000
balance = (balance - monthly_payment)
rateint = (balance / 100 * monthly_interest_rate)
mydist = ('Month: %d \n Minimum monthly payment: %g \n Remaining balance: %g \n Minimum Interest payment: %g'\
% (month, round(monthly_payment, 2), round(balance,2), round(rateint, 2)))
context={
'mylist': mydist
}
return render(request,'loantest.html',context)
else:
return render(request,'index.html')
else:
return render(request,'index.html')
在我的模板中:
{% for p in mylist %}
{{p}}
{% endfor %}
我认为您只是有一些小事情需要调整。这是我修复该代码的快速尝试。我已经内嵌添加了解释注释:
def sveloan(request):
if 'userid' in request.session:
if request.method == 'POST':
balance = 120000
annual_interest_rate = 42
monthly_payment_rate = 0.3
monthly_interest_rate = annual_interest_rate / 12
monthly_payment = monthly_payment_rate * balance
new_balance = (balance - monthly_payment) * (1 + monthly_interest_rate)
# setting up a collector here for the individual mydist tuples/rows
mylist = []
for month in range(1, 6):
monthly_payment = 20000
balance = (balance - monthly_payment)
rateint = (balance / 100 * monthly_interest_rate)
mydist = (
'Month: %d \n Minimum monthly payment: %g \n Remaining balance: %g \n Minimum Interest payment: %g' \
% (month, round(monthly_payment, 2), round(balance, 2), round(rateint, 2)))
# add each mydist tuple to the mylist collector
mylist.append(mydist)
# de-indeinting this, it should not be within your for loop
context = {
'mylist': mydist
}
return render(request, 'loantest.html', context)
else:
return render(request, 'index.html')
else:
return render(request, 'index.html')