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")
  1. Import necessary modules: HttpResponse from django.http, settings from django.conf, and os.

  2. Define a view function named download_file that takes a request object.

  3. Construct the file path by joining the MEDIA_ROOT setting from Django's settings with the file name 'file_to_download.txt'.

  4. Check if the file exists in the specified path.

  5. If the file exists, open it in binary read mode ('rb'), read its contents, and store it in the file variable.

  6. Create an HttpResponse object with the file's contents, specifying the content_type as 'application/force-download' to force the browser to download the file instead of displaying it.

  7. 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".

  8. Return the constructed response object.

  9. If the file does not exist, return an HttpResponse object with the message "File not found".