问题描述
在 views.py 中,我有以下函数来呈现 PDF 视图:
def agent_render_pdf(request,*args,**kwargs):
pk = kwargs.get('pk')
agent = get_object_or_404(Agents,pk=pk)
invoices = Invoice.objects.filter(agent=agent)
invoice_total = invoices.aggregate(Sum('invoice_amount'))
template_path = 'agents/statement.html'
context = {'agent': agent,'invoices':invoices,'invoice_total': invoice_total,}
#Create a Django response object,and specify content_type as pdf
response = HttpResponse(content_type='application/pdf')
#if download:
#response['Content-disposition'] = 'attachment'; filename"report.pdf"'
#if display:
response['Content-disposition']='filename="report.pdf"'
#find the template and render it
template = get_template(template_path)
html = template.render(context)
#create a PDF
pisa_status = pisa.CreatePDF(
html,dest=response
)
if pisa_status.err:
return HttpResponse('We had some errors <pre>' +html +'</pre>')
return response
我将其呈现为“statements.html”,如下所示:
<body>
{{ 代理 }}
<div class="table">
<table>
<th>Invoice Number</th>
<th>Invoice Date</th>
<th>Due Date</th>
<th>Invoice Amount</th>
<th>Invoice Age</th>
{% for i in invoices %}
<tr>
<td>{{ i.invoice_number }}</td>
<td>{{ i.invoice_date }}</td>
<td>{{ i.invoice_due_date|date:"m/d/Y" }}</td>
<td>{{ i.invoice_amount }}</td>
<td>{{ i.InvoiceAge }}</td>
</tr>
{% endfor %}
<tr>
<td> </td>
<td> </td>
<td>total:</td>
<td>${{ invoice_total }}</td>
<td> </td>
</tr>
</table>
</div>
我的视图基本上按预期呈现,接受invoice_total 显示为
${'invoice_amount__sum': 十进制('2500')}
而不是仅仅证明发票总额为 2,500 美元。我显然得到了我想要的信息,我只是不明白我做错了什么导致格式问题?
完整的PDF是:
解决方法
.aggregate()
返回一个字典,因为您可以同时获取多个聚合(想象一下一次选择一个计数、一个最大值和一个最小值,以避免多次查询)
所以只需设置一个密钥并使用它:
invoice_total = invoices.aggregate(total=Sum('invoice_amount'))['total']