Django – Export CSV report

Exporting CSV in Django would require changes in the view and template:

Template Code below, where hostedCustReport is the name of the view where the POST will be made

<button onclick="window.location='{% url hostedCustReport %}?export=true'" title="Export to CSV" class="button">
Export to CSV

View code – A separate section that checks for incoming GET protocol to return a CSV file. Otherwise, the normal flow to invoke the template with the locals that will be used to print the report on screen.

if request.GET.get('export', ''):
    response = HttpResponse(mimetype='text/csv')
    response['Content-Disposition'] = 'attachment; filename=hostedCustomerReport.csv'
    writer = csv.writer(response)
    writer.writerow(('Customer','SFID','Package','Support Expires'))
    for row in dataset:
        writer.writerow( (row['customer'], row['sfid'], row['package'], row['support_expires']) )
    return response

return render_to_response('reports/hosted_customer_report.html', locals(), context_instance=RequestContext(request))

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s