I am trying to convert a dictionary to csv and then download the csv file on the fly. When i return the response, I see the rows in the httpresponse. But I want it to download the content into a csv file in my local machine.
def export_csv_from_dict(data):
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="accounts.csv"'
keys = data[0].keys()
dict_writer = csv.DictWriter(response, keys)
dict_writer.writeheader()
dict_writer.writerows(data)
return response
def accounts_function(request):
# rows is a list of dictionary [{'name': 'a'}, {'name': 'b'}]
rows = get_rows_data(matched_accounts)
return data.export_csv_from_dict(rows)
I have tried many different method I saw on stackoverflow, such as filewrapper, using FileResponse, using writing to a temp file and returning it with filewrapper. Also tried using StringIO. None seems to be doing what I want to happen. Can someone explain what I am doing wrong, please. Thanks.
In chrome debugger, I see the proper content in the desired csv format. It won't pop up the download to computer window/action.
Here is now I am triggering it. Don't think this
$('#exp_csv').click(function(){
$.ajax({
'url': '/targeturl/',
'type': 'get',
data: {
'exp_csv': true,
'search_string': search
},
success: function(response){
// do something
},
error: function(){
// do something else
}
})
});