django force download file
from django.http import HttpResponse
from django.conf import settings
import os
def download_file(request):
file_path = os.path.join(settings.MEDIA_ROOT, 'file_to_download.txt')
if os.path.exists(file_path):
with open(file_path, 'rb') as file:
response = HttpResponse(file.read(), content_type='application/force-download')
response['Content-Disposition'] = 'attachment; filename="file_to_download.txt"'
return response
else:
return HttpResponse("File not found")
Import necessary modules:
HttpResponse
fromdjango.http
,settings
fromdjango.conf
, andos
.Define a view function named
download_file
that takes arequest
object.Construct the file path by joining the
MEDIA_ROOT
setting from Django's settings with the file name'file_to_download.txt'
.Check if the file exists in the specified path.
If the file exists, open it in binary read mode (
'rb'
), read its contents, and store it in thefile
variable.Create an
HttpResponse
object with the file's contents, specifying thecontent_type
as'application/force-download'
to force the browser to download the file instead of displaying it.Set the
Content-Disposition
header in the response to inform the browser that it should treat the content as an attachment and specify the filename as"file_to_download.txt"
.Return the constructed response object.
If the file does not exist, return an
HttpResponse
object with the message"File not found"
.