我在一本字典中有一些带有特定键的字典。现在我想动态访问模板中的每个键。我想使用主键作为表中的子标题,并在这些子标题下显示相关键的数据
我已经尝试了下面的代码,但它不工作
错误:
TemplateSyntaxError at /daily/report
Could not parse the remainder: '{{ledger}}' from 'ledgers.{{ledger}}
我怎样才能做到这一点
我的看法是:
@login_required
def accounts_report(request):
credit_vouchers = CreditVoucher.objects.all()
debit_vouchers = DebitVoucher.objects.all()
heads = AccountHead.objects.all()
opening_balance = request.GET.get('balance')
balance = float(opening_balance)
date_from = request.GET.get('from')
date_to = request.GET.get('to')
credit_vouchers = credit_vouchers.filter(date__gte=date_from, date__lte=date_to)
debit_vouchers = debit_vouchers.filter(date__gte=date_from, date__lte=date_to)
ledgers = {}
for head in heads:
key = head.head_name
ledgers.setdefault(key, [])
for item in ledgers:
key = item
ledgers.setdefault(key, [])
a_head = AccountHead.objects.get(head_name=key)
d_vouchers = debit_vouchers.filter(account_head=a_head)
c_vouchers = credit_vouchers.filter(account_head=a_head)
for voucher in d_vouchers:
balance -= voucher.amount
ledgers[key].append({
'date': voucher.date,
'description': voucher.description,
'voucher_no': voucher.voucher_serial,
'debit_amount': voucher.amount,
'credit_amount': 0,
'balance': balance,
})
for voucher in c_vouchers:
balance += voucher.amount
ledgers[key].append({
'date': voucher.date,
'description': voucher.description,
'voucher_no': voucher.voucher_serial,
'debit_amount': 0,
'credit_amount': voucher.amount,
'balance': balance,
})
context = {
'heads': heads,
'opening_balance': opening_balance,
'ledgers': ledgers
}
return render(request, 'accounts/report.html', context=context)
模板:
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
table.center {
margin-left: auto;
margin-right: auto;
}
</style>
</head>
<body>
<table>
<thead>
<tr>
<th>Voucher No</th>
<th>Date</th>
<th>Description</th>
<th>Debit</th>
<th>Credit</th>
<th>Balance</th>
</tr>
</thead>
<tbody>
<tr>
<td colspan="5">Opening Balance</td>
<td>{{opening_balance}}</td>
</tr>
{% for ledger in ledgers %}
<tr>
<td colspan="6">{{ledger}}</td>
</tr>
{% for item in ledgers.{{ledger}} %}
<tr>
<td>{{item.voucher_no}}</td>
<td>{{item.date}}</td>
<td>{{item.description}}</td>
<td>{{item.debit_amount}}</td>
<td>{{item.credit_amount}}</td>
<td>{{item.balance}}</td>
</tr>
{% endfor %}
{% endfor %}
</tbody>
</table>
</body>
</html>
将
ledgers.{{ledger}}
替换为ledger
在Django模板中使用动态键的唯一方法是写入a custom filter
您可以在
templatetags
文件夹中创建get_dictionnary_item.py
:然后您可以在模板中使用它:
相关问题 更多 >
编程相关推荐