Outputting CSV with Django

February 27, 2011

I wanted to output some data from my Django site, offering it as a CSV download. I did this using the Django template system.


Here's the template used, which is a simple for loop.

{% for result in ContestResults %}
"{{ result.contest_event.event_date }}","{{ result.contest_event.name }}","{{result.band_name}}"
{% endfor %}

Next, we need to render this template into a string in the view:

lCsvFile = render_to_string('bands/results.csv', {
                                                  "ContestResults" : lContestResults,

Finally, we set up the response and return the file.

lResponse = HttpResponse(mimetype="text/csv")
lResponse['Content-Disposition'] = "attachment; filename=%s.csv" % lBand.slug
return lResponse

The Content-Disposition header causes the browser to download the file rather than display it like a web page. We can dynamically control the default filename - here we're using the slug as the filename.