【发布时间】:2020-10-10 06:41:06
【问题描述】:
我正在尝试设置一个 django 按钮,以便我可以下载文件。我尝试按照教程进行操作,但我认为我遗漏了一些东西。下面的urls.py 代码是我在项目的应用程序部分生成的urls.py 文件。我不确定这是否是正确的使用方法。
下面的代码不起作用,本地主机不加载页面。但是,当我在我的urls.py 中注释掉url('download_my_pdf', download_pdf), 时,网站会加载,因为我们没有该链接返回视图中的代码。
索引.HTML:
<input type="button" value="Download" onclick="window.open('download_my_pdf')">
VIEWS.PY:
from django.shortcuts import render
from django.http import HttpResponse
from wsgiref.util import FileWrapper
def index(request):
return render(request, "index.html", {})
def home(request):
return render(request, "home.html", {})
def download_pdf(request):
filename = 'faults.pdf'
content = FileWrapper(filename)
response = HttpResponse(content, content_type='application/pdf')
response['Content-Length'] = os.path.getsize(filename)
response['Content-Disposition'] = 'attachment; filename=%s' % 'faults.pdf'
return response
URLS.PY
from django.urls import url
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name="index"),
path('home', views.home, name="home"),
url('download_my_pdf', download_pdf),
]
【问题讨论】:
-
更新
url('download_my_pdf', download_pdf),______________ 到 _____________path('download_my_pdf', views.download_pdf), -
当网站加载很好时,但是当我现在单击下载按钮时,它会抛出“str”对象没有属性“读取”错误。所以实际上没有下载文件。它在我的views.py中点亮第16行: response = HttpResponse(content, content_type='application/pdf')
标签: python html django django-views