Django Serving a Download File Django Serving a Download File django django

Django Serving a Download File


Have you considered just sending p.body through the response like this:

response = HttpResponse(mimetype='text/plain')response['Content-Disposition'] = 'attachment; filename="%s.txt"' % p.uuidresponse.write(p.body)


XSend requires the path to the file in response['X-Sendfile']So, you can do

response['X-Sendfile'] = smart_str(path_to_file)

Here, path_to_file is the full path to the file (not just the name of the file)Checkout this django-snippet


There can be several problems with your approach:

  • file content does not have to be flushed, add f.flush() as mentioned in comment above
  • NamedTemporaryFile is deleted on closing, what might happen just as you exit your function, so the webserver has no chance to pick it up
  • temporary file name might be out of paths which web server is configured to send using X-Sendfile

Maybe it would be better to use StreamingHttpResponse instead of creating temporary files and X-Sendfile...