2012-01-12 81 views
0

我试图显示每个用户在我的模板上的表格中获得的总金额。现在,当我在控制台中打印语句时,我得到了正确的值,但是当我在模板上放置{{ total_dollar_amount }}时,它只显示最后一个值。模板无法显示正确的计算值

现在我认为我应该通过total_dollar_amount循环,但它会抛出一个错误,说十进制值是不可迭代的。

任何人都知道我错过了什么?

views.py

def ABD_report(request, *args, **kwargs): 
""" 
This report will show all 'In Trust For' investments in the system and display all relevant information 
""" 
from investments.models import Investment 
from reports.forms import InTrustForm 
context = {} 
if request.POST: 
    form = InTrustForm(request.agents, request.POST) 
    if form.is_valid(): 
     agents = form.cleaned_data['agents'] 
     context['selected_agents'] = agents 
     investments = Investment.objects.filter(plan__profile__agent__in=agents, plan__ownership_type__code = "itf") 
     for i in investments: 
      #count all members in each plan 
      count = i.plan.planmember_set.all().count() 
      #take off the primary member of the account 
      count -= 1 
      if i.interestoption: 
       if i.interestoption.short_label == 'AN': 
        pay_amt = i.pay_amount 
        total_amt = (pay_amt/count) 
        context['total_dollar_amt'] = total_amt 
      context['counted'] = count 
     context['investments'] = investments 
     context['show_report'] = True 
else: 
    form = InTrustForm(request.agents) 

context['form'] = form 

return render_to_response('reports/admin/abd_report.html', RequestContext(request, context)) 

回答

1

context变量是字典;每个键只能有一个值。您正在通过循环investments并在每个循环上设置相同的两个键context['total_dollar_amt']context['counted'] - 因此在每次迭代中您都会覆盖之前的值。

如果你希望能够通过每项投资的countedtotal_dollar_amt值循环,你需要这个附加的投资对象,而不是设置在context的关键:在你的模板

for i in investments: 
    #count all members in each plan 
    count = i.plan.planmember_set.all().count() 
    #take off the primary member of the account 
    count -= 1 
    if i.interestoption: 
     if i.interestoption.short_label == 'AN': 
      pay_amt = i.pay_amount 
      total_amt = (pay_amt/count) 
      # attach value to the investment 
      i.total_dollar_amt = total_amt 
    # attach value to the investment 
    i.counted = count 

现在,你可以通过investments循环。

1

context['total_dollar_amt']被覆盖掉了每次分配得到的循环打时间。要查看将传递给模板的值,请在render_to_response之前执行print context['total_dollar_amt']

从你的描述中我不完全清楚,但是我认为你需要将一系列的字典传递给上下文,而不是像context['investments_data'] = [],然后在循环中,context['investments_data'].append({'inv': i, 'total_dollar_amt': total_amt})或类似的。然后在模板中:

{% for inv_data in investments_data %} 
    {{ inv_data.inv.name }} total: {{ inv_data.total_amt }} 
{% endfor %}