tmaster tmaster - 4 months ago 33
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 urls.py 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:

$('#download_button').click(function(){
$.get('/reports/csv_list_report/');
});


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

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:

location.replace('/reports/csv_list_report/');

Related: Force download through js or query

Comments