Как позволить пользователям загружать файл excel по определенному пути в Django?

Я начинающий в Python Django. Я пытаюсь позволить пользователям загружать файл excel по определенному пути в Django. Мой views.py выглядит следующим образом. Как вы можете видеть, я хочу позволить пользователю загрузить файл OOOO.xlsx по пути /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

Мой urls.py выглядит следующим образом.

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

Однако, он продолжает показывать ошибку, подобную этой, на моей HTML странице.

<enter image description here>

Пожалуйста, помогите мне найти ошибку.

Вам следует использовать djangos FileResponse. Подробнее читайте здесь.

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)
Вернуться на верх