Generating file to download with Django

To trigger a download you need to set Content-Disposition header:

from django.http import HttpResponse
from wsgiref.util import FileWrapper

# generate the file
response = HttpResponse(FileWrapper(myfile.getvalue()), content_type="application/zip")
response['Content-Disposition'] = 'attachment; filename=myfile.zip'
return response

If you don’t want the file on disk you need to use StringIO

import cStringIO as StringIO

myfile = StringIO.StringIO()
while not_finished:
    # generate chunk
    myfile.write(chunk)

Optionally you can set Content-Length header as well:

response['Content-Length'] = myfile.tell()

Leave a Comment