0

In views.py, I have the following function to render a PDF view:

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

I am rendering that to 'statements.html' as follows:

<body>

{{ agent }}


<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>&nbsp;</td>
            <td>&nbsp;</td>
            <td>total:</td>
            <td>${{ invoice_total }}</td>
            <td>&nbsp;</td>
        </tr>

    </table>
</div>

My view is basically rendering as expected, accept that the invoice_total is showing up as

${'invoice_amount__sum': Decimal('2500')}

instead of just proving the total of invoices as $2,500. I'm clearly getting the information I want, I just don't understand what I'm doing wrong that's causing the formatting issue?

The full PDF is:

Screen capture of PDF output

FaxMeBeer
  • 1
  • 1

1 Answers1

0

.aggregate() returns a dictionary, because you can get several aggregates at the same time (imagine selecting a count, a max, and a min at once, to avoid multiple queries)

So just set a key and use it:

invoice_total = invoices.aggregate(total=Sum('invoice_amount'))['total']
Tim Nyborg
  • 1,599
  • 1
  • 9
  • 16