Menu Close

How to generate file to download with Python Django?

To generate file to download with Python Django, we can use the HttpResponse class.

For instance, we write

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

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

to generate the download file in our view by creating a HttpResponse object.

We call myfile.getvalue() to get the file and wrap it with FileWrapper where myfile is a Django File object.

And then we set the Content-Disposition header with

response['Content-Disposition'] = 'attachment; filename=myfile.zip'

And finally, we return the response.

Posted in Python, Python Answers