我试图通过Django管理员上传一个图像,然后在前端的页面或只是通过URL查看该图像。

注意,这些都在我的本地机器上。

我的设置如下:

MEDIA_ROOT = '/home/dan/mysite/media/'

MEDIA_URL = '/media/'

我已经将upload_to参数设置为'images',文件已经正确上传到目录:

'/home/dan/mysite/media/images/myimage.png'

然而,当我试图访问下面的URL图像:

http://127.0.0.1:8000/media/images/myimage.png

我得到一个404错误。

我是否需要为上传的媒体设置特定的URLconf模式?

任何建议都很感激。

谢谢。


当前回答

将下面的代码添加到"settings.py"来访问(打开或显示)上传的文件:

# "urls.py"

from django.conf import settings
from django.conf.urls.static import static

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

其他回答

在设置完所有URLconf模式后,您可能面临的另一个问题是变量{{MEDIA_URL}}在模板中不起作用。要解决这个问题,在settings.py中,确保添加

django.core.context_processors.media

在TEMPLATE_CONTEXT_PROCESSORS中。

对于调试模式,执行上述步骤=>3.0

urlpatterns = [
...
]
+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

这也是我发现的部分,上面的静态URL只在我的主项目urls.py文件中工作。我第一次尝试添加到我的应用程序,并想知道为什么我不能看到图像。

最后确保你设置了以下内容:

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

这是我在Python 3.6和Django 1.11中使用DEBUG = False模式实现图像渲染的方法

from django.views.static import serve
urlpatterns = [
url(r'^media/(?P<path>.*)$', serve,{'document_root': settings.MEDIA_ROOT}),
# other paths
]

我是否需要为上传的媒体设置特定的URLconf模式?

是的。对于开发,这就像添加到你的URLconf一样简单:

if settings.DEBUG:
    urlpatterns += patterns('django.views.static',
        (r'media/(?P<path>.*)', 'serve', {'document_root': settings.MEDIA_ROOT}),
    )

然而,对于生产,你会想要使用Apache、lighttpd、nginx或你喜欢的web服务器来服务媒体。

下面是我使用Django 1.10.6为Django -publications应用程序交付pdf文件所做的更改:

在settings.py中使用与您相同的媒体目录定义:

MEDIA_ROOT = '/home/user/mysite/media/'

MEDIA_URL = '/media/'

由@thisisashwanipandey提供,在项目的主要urls.py中:

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    # ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

在settings.py中,对@r-allela提供的答案进行了修改:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                # ... the rest of your context_processors goes here ...
                'django.template.context_processors.media',
            ],
         },
    },
]