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

任何建议都很感激。

谢谢。


当前回答

加入Micah Carrick对django 1.8的回答:

if settings.DEBUG:
  urlpatterns.append(url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}))

其他回答

请仔细阅读Django官方文档,你会找到最合适的答案。

解决这个问题的最好和最简单的方法如下。

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)

如果您使用的是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.9,你需要根据文档添加以下代码:

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)

欲了解更多信息,请访问:https://docs.djangoproject.com/en/1.9/howto/static-files/#serving-files-uploaded-by-a-user-during-development

对于开发中的Django 3.0+,在你的主url .py中包含以下内容:

urlpatterns = [
   # rest of your url paths here..
]

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) +
        static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
        )

将下面的代码添加到"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)