如何从Django管理员下载文件 [英] How to download file from django admin
问题描述
我在 models.py 的 class Part 中创建了 FileField .我也通过方法 file_link(self)
I created FileField in class Part in models.py. Also I get the link of this file by method file_link(self):
origin = models.FileField(upload_to='origin_files', null=True, blank=True)
def file_link(self):
try:
return "<a href='%s'>download</a>" % (self.origin.url,)
except PageNotAnInteger:
return "<a href=127.0.0.1:8000/main>download</a>"
file_link.allow_tags = True
在admin.py中,我为 file_link 添加了 readonly_fields .我也添加了字段集 file_link :
In admin.py I added readonly_fields for file_link. Also I added in fieldsets file_link:
readonly_fields = ('file_link',)
fieldsets = (
('Характеристики плёнки', {
'fields': (....'data', 'origin', 'file_link')
}),
)
因此,在我的Django管理员中,我有FileField,它允许将文件上传到目录 origin_files 并链接到该文件.但是,当我单击此链接时,我将重定向到我网站的主页.例如,我下载了文件presentation.pptx.当我获得该文件的网址时,我会得到
So, in my django admin I have FileField which allows to upload files to directory origin_files and link to this file. But when I click on this link I'm redirecting to home page of my site. For example, I downloaded file presentation.pptx. When I get url of this file I get
http://127.0.0.1:8000/admin/description/part/12/change/origin_files/Presentation.pptx
我如何下载此文件?
推荐答案
您必须在Django设置中配置 MEDIA_URL
You have to configure MEDIA_URL
in your django settings
https://docs.djangoproject.com/en/2.0/ref/settings/#media-url
Django通过以下方式构建您的网址:
Django builds your url the following way:
settings.MEDIA_URL +"origin_files/Presentation.pptx"
settings.MEDIA_URL + "origin_files/Presentation.pptx"
MEDIA_URL的默认值是一个空字符串,因此您获得的URL为"origin_files/Presentation.pptx",并且您的浏览器将其连接到当前页面,因为该URL并非以斜杠开头.
the MEDIA_URL default is an empty string, therefore you get the url "origin_files/Presentation.pptx" and your browser concatenates it to the current page, because the url doesn't start with a slash.
所以您必须将MEDIA_URL设置为'/media/'
so you have to set the MEDIA_URL for example to '/media/'
然后一切都将在您的开发环境中工作.
then everything will work in your development environment.
在远程服务器上,这还需要适当地配置Web服务器,以便将您的MEDIA_ROOT服务到MEDIA_URL(显然超出了此问题的范围).
On remote server this also requires configuring the web server appropriatelly for it to serve your MEDIA_ROOT to MEDIA_URL (out of the scope of this question obviously).
这篇关于如何从Django管理员下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!