我想从媒体文件中提供我的下载文件,并且正在从管理员上传文件。我尝试了一些东西,但出现此错误
TypeError at /1
argument should be string, bytes or integer, not Download
下面是我的代码。
查看.py
def download(request, download_id):
downloading = Download.objects.get(pk=download_id)
if os.path.exists(downloading):
with open(downloading, 'rb') as fh:
response = HttpResponse(fh.read(), content_type="text/pdf")
response['Content-Disposition'] = 'inline; filename=' + os.path.basename(downloading)
response['Content-Length'] = os.path.getsize(downloading)
return response
pdf.closed
raise Http404
网址.py
url(r'^(?P<download_id>\d+)$', views.download, name='download'),
html链接
<a href="{% url 'peruse:download' download.id %}" class="btn btn-generic btn-sm" role="button">DOWNLOAD</a>
模型.py
class Download(models.Model):
pdf_name = models.CharField(max_length=500, blank=False)
pdf_file = models.FileField(upload_to='Downloads/%d-%m-%Y/', blank = False,)
created_at = models.DateTimeField(auto_now_add = True)
updated_at = models.DateTimeField(auto_now = True)
is_visible = models.BooleanField(default = True)
def __str__(self):
return self.pdf_name
这个视图处理上传。
def upload(request):
uploading = Download.objects.filter(is_visible = True)
context = { 'uploading' : uploading }
fillAuthContext(request, context)
return render(request, 'library/resources.html', context)
谢谢大家的帮助。我能够想出一些符合你的想法的东西。
查看.py
def download(request, download_id):
downloading = Download.objects.get(pk=download_id)
path = downloading.pdf_file.name
file_path = os.path.join(settings.MEDIA_ROOT, path)
if os.path.exists(file_path):
with open(file_path, 'rb') as pdf:
response = HttpResponse(pdf.read(), content_type="text/pdf")
response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path)
response['Content-Length'] = os.path.getsize(file_path)
return response
pdf.closed
raise Http404
它现在工作。用户现在可以下载文件
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句