Categories
Python Answers

How to have Django serve downloadable files with Python?

Spread the love

Sometimes, we want to have Django serve downloadable files with Python.

In this article, we’ll look at how to have Django serve downloadable files with Python.

How to have Django serve downloadable files with Python?

To have Django serve downloadable files with Python, we can return a file download response in our view.

For instance, we write

from django.utils.encoding import smart_str

response = HttpResponse(content_type='application/force-download') 
response['Content-Disposition'] = 'attachment; filename=%s' % smart_str(file_name)
response['X-Sendfile'] = smart_str(path_to_file)
return response

to create a HttpResponse object that has the content_type argument set to 'application/force-download'.

Then we set the Content-Disposition response header to 'attachment; filename=%s' % smart_str(file_name).

Next, we set the X-Sendfile response header to smart_str(path_to_file).

Now the response should download the file at path_to_file.

And then we return the response.

Conclusion

To have Django serve downloadable files with Python, we can return a file download response in our view.

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 *