2

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.

NoobEditor
  • 15,563
  • 19
  • 81
  • 112
tmaster
  • 9,345
  • 6
  • 24
  • 27

1 Answers1

7

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

Community
  • 1
  • 1
Elias Dorneles
  • 22,556
  • 11
  • 85
  • 107
  • Great, that was the problem. Cheers! – tmaster Dec 19 '12 at 11:47
  • Would it be a problem that I get a warring from the browser console "Resource interpreted as Document but transferred with MIME type text/csv: " – tmaster Dec 19 '12 at 11:52
  • 1
    I think that's just a Chrome behavior, it seems you can ignore that, see: http://stackoverflow.com/questions/3899426/resource-interpreted-as-document-but-transferred-with-mime-type-text-css – Elias Dorneles Dec 19 '12 at 11:59