在Django中执行管理操作来下载用户的PDF文件,可以通过以下步骤实现:
from django.http import HttpResponse
from django.conf import settings
import os
def download_pdf(request, file_name):
file_path = os.path.join(settings.MEDIA_ROOT, file_name)
if os.path.exists(file_path):
with open(file_path, 'rb') as pdf:
response = HttpResponse(pdf.read(), content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename="{}"'.format(file_name)
return response
else:
return HttpResponse("File not found.")
from django.urls import path
from . import views
urlpatterns = [
path('download_pdf/<str:file_name>/', views.download_pdf, name='download_pdf'),
]
<a href="{% url 'download_pdf' file_name %}">Download PDF</a>
其中,file_name
是你要下载的PDF文件的文件名。
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
然后,将你的PDF文件保存在媒体文件夹中。
这样,当用户点击下载链接时,Django将会执行相应的管理操作,从媒体文件夹中读取并下载用户的PDF文件。
1 将文件保存到服务器本地
upload.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<form action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
领取专属 10元无门槛券
手把手带您无忧上云