我试图通过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模式?

任何建议都很感激。

谢谢。


当前回答

这是我在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
]

其他回答

这是我在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
]

如果您使用的是python 3.0+,则按以下方式配置您的项目

设置

STATIC_DIR = BASE_DIR / 'static'
MEDIA_DIR = BASE_DIR / 'media'
MEDIA_ROOT = MEDIA_DIR
MEDIA_URL = '/media/'

主要的url

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

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

如果是Django 1.10:

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

对于调试模式,执行上述步骤=>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/'

下面是我使用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',
            ],
         },
    },
]