我对使用Django很陌生,我正在努力开发一个网站,用户可以在帖子结束时下载文件。文章模型:
class Article(models.Model):
title = models.CharField(max_length=30)
content = models.TextField()
pub_date = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
file = models.FileField(upload_to='code_files/')
def __str__(self):
return self.title
I have a views:
def download(request):
response = HttpResponse(open(f"media/code_files/tests.py", 'rb').read())
response['Content-Type'] = 'text/plain'
response['Content-Disposition'] = f'attachment; filename=tests.py'
return response
我如何下载与文章链接的文件?
From Dajngo docsfilerresponse是StreamingHttpResponse
的子类,对二进制文件进行了优化。
import os
from django.http import FileResponse
from django.views.decorators.http import require_POST
@require_POST
def download(request):
article = Article.objects.get(id=1)
fullpath = article.file.path
if not os.path.exists(fullpath):
raise Http404('{0} does not exist'.format(fullpath))
return FileResponse(
open(fullpath, 'rb'), as_attachment=True,
filename=article.file.name)
假设您将Article对象作为上下文从视图传递给模板。
context = {
'article' = article_obj,
}
在你的HTML中,你需要使用嵌入标签和Article对象的FileField的url。
<embed src="{{article.file.url}}" width="500" height="200">
您不应该仅仅为了下载文件而编写另一个视图。只要将文章放在你想要显示下载链接的视图中:
context = {'article': Article.objects.first()}
确保在设置中也添加了媒体URL:
MEDIA_URL = "/media/"
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
和项目url .py:
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
然后,对于你的文章模型,给每篇文章一个格式化的文件url:
class Article(models.Model):
@property
def formatted_file_url(self):
if self.file:
return settings.MEDIA_URL + self.file.url
else:
return 'No url'
下载:
<a href="{{ article.formatted_file_url }}" download>