Categories
Python Answers

How to generate file to download with Python Django?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *