管理员FileField当前网址不正确 [英] Admin FileField current url incorrect
问题描述
在Django管理员中,无论我有一个FileField,在编辑页面上都有一个当前"框,其中包含指向当前文件的超链接.但是,此链接被附加到当前页面的URL,因此由于没有这样的页面,因此将导致404,例如: http://127.0.0.1:8000/admin/Tank/asset/17/media/datasheet/13/09/05/copyright.html/
作为参考,文件的正确网址是: http://127.0.0.1:8000/media/datasheet/13/09/05/copyright.html
In the Django admin, wherever I have a FileField, there is a "currently" box on the edit page, with a hyperlink to the current file. However, this link is appended to the current page url, and therefore results in a 404 as there is no such page as, for example:
http://127.0.0.1:8000/admin/Tank/asset/17/media/datasheet/13/09/05/copyright.html/
For reference, the correct url of the file is:
http://127.0.0.1:8000/media/datasheet/13/09/05/copyright.html
有没有办法解决默认管理员布局中的此问题?它会影响数据库中的每个FileField,在我看来,这就像一个错误.我只是用错了吗?
Is there any way to fix this problem in the default admin layout? It affects every FileField in my database, and seems to me like a bug. Am I just using it wrong?
推荐答案
settings.py
添加行:
import os
BASE_DIR = os.path.realpath(os.path.dirname(__file__))
替换行:
MEDIA_ROOT = ''
MEDIA_URL = ''
使用
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR,os.pardir,'media')
这应该设置您的项目以呈现文件夹/your project directory/media/
this should setup your project to render your media content from the folder /your project directory/media/
还添加以下行:
import settings
在您的网址格式中添加以下行:
add the following line in your url patterns:
url(r'^media/(?P<path>.*)$', 'django.views.static.serve',{'document_root': settings.MEDIA_ROOT, 'show_indexes': False}),
models.py
在模型内部添加以下行:
models.py
inside your model add the following line:
File = models.FileField('File',upload_to='./')
定义模型中的方法
def fileLink(self):
if self.File:
return '<a href="' + str(self.File.url) + '">' + 'NameOfFileGoesHere' + '</a>'
else:
return '<a href="''"></a>'
fileLink.allow_tags = True
fileLink.short_description = "File Link"
admin.py
使用字段 fileLink
作为只读字段,您也可以将其添加到 list_display
admin.py
use the field fileLink
as a read only field, you can also add it to your list_display
例如
class FileAdmin(admin.ModelAdmin):
list_display = ['fileLink']
readonly_fields = ['fileLink']
这篇关于管理员FileField当前网址不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!