To download a file with Python Django, we can return a response with the download file.
For instance, we write
import os
from django.conf import settings
from django.http import HttpResponse, Http404
def download(request, path):
file_path = os.path.join(settings.MEDIA_ROOT, path)
if os.path.exists(file_path):
with open(file_path, 'rb') as fh:
response = HttpResponse(fh.read(), content_type="application/vnd.ms-excel")
response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path)
return response
raise Http404
to create the download
view that gets the file from file_path
if it exists.
We call open
to open the file.
And the we create a HttpResponse
with the Content-Disposition
header set.
We set the content_type
when we create the HttpResponse
to the MIME type of the file downloaded.
And fh.read()
has the download file content.
Then we return the response.
If the file isn’t found, then we return a 404 error with raise Http404
.