tmaster tmaster - 1 year ago 140
Python Question

How to make browser to download the Django CSV file response

I am following the Django doc here to create a CSV file. In my I have

url(r'^reports/csv_list_report/$', 'csv_list_report')

I want user to download the CSV file when clicking on the download button. So I use jQuery for here:


I can see the response in the firebug, but the browser does not download the file.

Here is my view:

def csv_list_report(request):
response = HttpResponse(mimetype='text/csv')
response['Content-Disposition'] = 'attachment; filename="reports.csv"'
writer = csv.writer(response)
writer.writerow(['First row', 'Foo', 'Bar', 'Baz'])
writer.writerow(['Second row', 'A', 'B', 'C', '"Testing"', "Here's a quote"])

return response

So maybe after the GET I need to write something to handle the response on success? Searched around, there are plenty answers on how to create CSV files, but didn't find any answers including what one need to do to handle the response.

Answer Source

You can't make the browser download a file through AJAX (that's what jQuery is doing when you use $.get). You have to make a direct synchronous HTTP connection.

Instead of $.get, try this:


Related: Force download through js or query

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download