Django 在/下载时发生许可错误/

Django 在/下载时发生许可错误/,django,python-3.x,Django,Python 3.x,当我尝试下载该文件时,它在/download处显示PermissionError/ 视图.py 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 f: response = HttpResponse(f.read(), co

当我尝试下载该文件时,它在/download处显示PermissionError/

视图.py

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 f:
        response = HttpResponse(f.read(), content_type="application/vnd.ms-excel")
        response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path)
        return response
   raise Http404
re_path(r'^download/(?P<path>.*)$', views.download)
url.py

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 f:
        response = HttpResponse(f.read(), content_type="application/vnd.ms-excel")
        response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path)
        return response
   raise Http404
re_path(r'^download/(?P<path>.*)$', views.download)

任何帮助都将不胜感激)这个问题已经让我恼火了一周了

您的路径是空的,因此它正在尝试打开作为目录的
MEDIA\u ROOT

假设您的目录结构如下所示:

-media root
  - 1.xlsx
然后将tour html更新为

<a href="/download/1.xlsx">Download</a>


因此,您的路径变量变为1.xlsx

这是我的媒体根目录'media\u root=os.path.join(BASE\u dir,'media/')请告诉我如何打开?我打开了上面存在的路径code@JibinMathews非常感谢)终于成功了,但还有一件事请告诉我文件类型只能是pdf或ppt,doc。现在有更多的文件,我只指定了1.xlsx,我如何在url中指定,并限制文件类型仅用于pdf文档和ppt。非常感谢。beforehand@coder在视图中,您可以使用
分割路径,并检查它是否与有效类型的数组匹配