我有一个可以在管理页面中编辑的模型。我想上传文件,然后再下载回来。
在型号中:
class Project(models.Model):
project_title = models.CharField(max_length=200)
project_content = models.TextField()
project_published = models.DateTimeField("date published", default=datetime.now())
project_file = models.FileField(default="Null",upload_to='Files')
def __str__(self):
return self.project_title
在管理员中:
class ProjectAdmin(admin.ModelAdmin):
#fields = ["project_title",
# "project_published",
# "project_content",
# "project_funded",]
fieldsets = [
("Title/date", {"fields": ["project_title", "project_published"]}),
("URL", {"fields":["project_slug"]})
("Content", {"fields":["project_content", "project_file"]}),
]
FileField生成2个子字段:一个上载按钮,以及一个“当前”字段,如果存在,则带有指向当前文件的链接。
文件上传工作正常,文件存储在“文件”目录中,但是当我单击链接时,我被重定向到主页并获得“ ID为“ 1 / change / Files / somefilename”的项目”存在。也许它被删除了?”错误。
我尝试添加到管理员中
def file_link(self, Project):
if Project.project_file:
return "<a href='%s' download>Download</a>" % (Project.project_file.url,)
else:
return "No attachment"
file_link.allow_tags = True
file_link.short_description = 'File Download'
,但它只是将href打印为纯文本,其中包含“文件/文件名” URL。
服务器最后处理的请求:
[10 / Oct / 2019 15:57:15]“ GET /admin/main/project/1/change/Files/61765395_604632376708720_5004719923088326656_n_1_zAanPtO.jpg HTTP / 1.1” 301 0 [10 / Oct / 2019 15:57:15]“ GET /admin/main/project/1/change/Files/61765395_604632376708720_5004719923088326656_n_1_zAanPtO.jpg/ HTTP / 1.1” 302 0 [10 / Oct / 2019 15:57:15]“ GET /admin/main/project/1/change/Files/61765395_604632376708720_5004719923088326656_n_1_zAanPtO.jpg/change/ HTTP / 1.1” 302 0 [10 / Oct / 2019 15:57:15]“ GET / admin / HTTP / 1.1” 200 7848
答案 0 :(得分:0)
可能您需要像这样修复MEDIA_URL
:
MEDIA_URL = '/media/'
并在urls.py中添加媒体URL,以允许django提供您的媒体文件(in development server
):
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = patterns('',
# ... the rest of your URLconf goes here ...
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)