Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/296.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 管理员文件字段当前url不正确_Python_Django_Django Admin_Filefield - Fatal编程技术网

Python 管理员文件字段当前url不正确

Python 管理员文件字段当前url不正确,python,django,django-admin,filefield,Python,Django,Django Admin,Filefield,在Django管理员中,无论我在哪里有一个文件字段,编辑页面上都有一个“当前”框,其中包含指向当前文件的超链接。但是,此链接附加到当前页面url,因此会导致404,因为没有这样的页面,例如: http://127.0.0.1:8000/admin/Tank/asset/17/media/datasheet/13/09/05/copyright.html/ 作为参考,文件的正确url为: http://127.0.0.1:8000/media/datasheet/13/09/05/copyrigh

在Django管理员中,无论我在哪里有一个文件字段,编辑页面上都有一个“当前”框,其中包含指向当前文件的超链接。但是,此链接附加到当前页面url,因此会导致404,因为没有这样的页面,例如:
http://127.0.0.1:8000/admin/Tank/asset/17/media/datasheet/13/09/05/copyright.html/

作为参考,文件的正确url为:
http://127.0.0.1:8000/media/datasheet/13/09/05/copyright.html


有没有办法在默认的管理布局中解决这个问题?它会影响我数据库中的每个文件字段,在我看来就像一个bug。我只是用错了吗?

这个问题的答案已经完全被我的文章涵盖了。不过,简而言之,问题在于您可能没有在settings.py和url.py中设置媒体根目录和媒体,因此您没有设置媒体文件夹

有关如何做这些事情的详细信息,请查看令人难以置信的精彩答案。

settings.py 添加以下行:

import os
BASE_DIR = os.path.realpath(os.path.dirname(__file__))
MEDIA_ROOT = ''
MEDIA_URL = ''
更换管路:

import os
BASE_DIR = os.path.realpath(os.path.dirname(__file__))
MEDIA_ROOT = ''
MEDIA_URL = ''

这将设置项目以呈现文件夹/项目目录/媒体中的媒体内容/

url.py 同时添加以下行:

import settings
在url模式中添加以下行:

url(r'^media/(?P<path>.*)$', 'django.views.static.serve',{'document_root': settings.MEDIA_ROOT, 'show_indexes': False}),
在模型中定义方法

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"

已经有一段时间了,但是,你知道为什么我不使用链接,而是将HTML a元素作为字符串显示在表单中,而不是实际的链接中吗?(在Django 2.x中)
class FileAdmin(admin.ModelAdmin):
    list_display = ['fileLink']
    readonly_fields = ['fileLink']