【发布时间】:2017-05-27 08:31:49
【问题描述】:
我想从媒体文件中提供我的下载文件,并且这些文件正在通过管理员上传。我尝试了一些东西,但我收到了这个错误
TypeError at /1
argument should be string, bytes or integer, not Download
以下是我的代码。
view.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
url.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>
model.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)
【问题讨论】:
-
请格式化您的代码,整篇文章真的很难阅读
-
格式化谢谢
-
正在尝试使用我在这里看到的 stackoverflow.com/questions/36392510/django-download-a-file。请随时纠正您发现的任何错误。使用 django 不太好。谢谢
-
错误发生在哪一行?是
open吗?请发布您的整个错误消息和回溯。Download来自哪里? -
downloading应该是您的download file path字符串,而不是Download对象。