【发布时间】:2021-10-10 19:07:53
【问题描述】:
我在 django 中有一个应用程序,它执行一些流程并构建一个文件,在一个部分中,我想向用户展示该文件以下载该文件。
(例如,用户在前端输入一个名字,应用程序给他一个 pdf 文件供他下载)。
文件构建过程正常,位于/app_dir/media/app/report/username/file.pdf
这是我的代码,但它不起作用,我遇到了一些问题。
你能帮帮我吗,我的问题在哪里?
以及如何使该用户特定于?每个用户都可以访问他的文件。
views.py (my_main_function):
@login_required(login_url='/login/')
def my_function(request):
if request.method == 'GET':
return render(request, 'app/my_function.html')
else:
try:
#my main process to build .PDF file
except ValueError:
return render(request, 'app/dashboard.html', {'error':'Bad data passed in. Try again.'})
return render(request, 'app/download.html')
views.py(下载功能):
def download_file(request):
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
filename = f"{file}.pdf"
# Define the full file path
filepath = f"{BASE_DIR}/app/media/app/reports/{user_name}/{filename}"
# Open the file for reading content
path = open(filepath, 'rb')
path.read()
# Set the return value of the HttpResponse
response = HttpResponse(path, content_type='application/pdf')
# Set the HTTP header for sending to browser
response['Content-Disposition'] = "attachment; filename=%s" % filepath
# Return the response value
return response
urls.py:
path('download/', views.download_file, name='download_file'),
简单测试下载.html文件:
<html>
<title>Download File</title>
</head>
<body>
<enter>
<h1>Download File using link</h1>
<a href="{% url 'download_file' %}">Download PDF</a>
</center>
</body>
</html>
【问题讨论】:
-
请将您的代码以文本形式发布,Stack Overflow 不接受截图。
-
@KlausD。抱歉,我编辑了它并添加了代码。
标签: python python-3.x django django-views