Skip to content

Instantly share code, notes, and snippets.

@reidransom
Last active June 27, 2022 16:03
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save reidransom/a397cd2fb7d489ef3049 to your computer and use it in GitHub Desktop.
Save reidransom/a397cd2fb7d489ef3049 to your computer and use it in GitHub Desktop.
Returning binary data from a Django view
from django.http import HttpResponse
def django_file_download_view(request):
filepath = '/path/to/file.xlsx'
with open(filepath, 'r') as fp:
data = fp.read()
filename = 'some-filename.xlsx'
response = HttpResponse(mimetype="application/ms-excel")
response['Content-Disposition'] = 'attachment; filename=%s' % filename # force browser to download file
response.write(data)
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment