[Solved]-Django generate csv file on view and download

23👍

you’re passing the handle of the file being written (and not sure of your indentation, you could just be outside the with block.

Just reopen it in read mode.

with open('stockitems_misuper.csv', 'w', newline="") as myfile:  # python 2: open('stockitems_misuper.csv', 'wb')
    wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
    wr.writerows(file_rows)

with open('stockitems_misuper.csv') as myfile:
    response = HttpResponse(myfile, content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename=stockitems_misuper.csv'
    return response

or better: write to a io.StringIO() instance, and pass that, avoiding to create the file.

import io,csv

buffer = io.StringIO()  # python 2 needs io.BytesIO() instead
wr = csv.writer(buffer, quoting=csv.QUOTE_ALL)
wr.writerows(file_rows)

buffer.seek(0)
response = HttpResponse(buffer, content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename=stockitems_misuper.csv'

return response

Leave a comment