How to let users download an excel file in a specific path in Django?

I am a beginner in Python Django. I am trying to let users download an excel file in a specific path in Django. My views.py is as follows. As you can see, I want to let user download OOOO.xlsx in the path /mysite/upload/.

def download_file(request):
    # Define Django project base directory
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    # Define file name
    filename = 'OOOO.xlsx'
    # Define the full file path
    filepath = BASE_DIR + '/mysite/upload/' + filename
    # Open the file for reading content
    path = open(filepath, 'r')
    # Set the mime type
    mime_type, _ = mimetypes.guess_type(filepath)
    # Set the return value of the HttpResponse
    response = HttpResponse(path, content_type=mime_type)
    # Set the HTTP header for sending to browser
    response['Content-Disposition'] = "attachment; filename=%s" % filename
    # Return the response value
    return response

My urls.py is as follows.

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',views.index),
    path('download/', views.download_file),
]

However, it keeps showing an error like this on my HTML page.

<enter image description here>

Please help me to find the bug.

You should use djangos FileResponse. Read here for more.

def download_file(request):
    # Define Django project base directory
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    # Define file name
    filename = 'OOOO.xlsx'
    # Define the full file path
    filepath = BASE_DIR + '/mysite/upload/' + filename
    return FileResponse(open(filepath, 'rb'), as_attachment=True)
Back to Top