Django: MEDIA_URL returns Page Not Found

扶醉桌前 提交于 2019-12-04 07:48:56

Just a quick example of what works for me on one my projects.
settings.py

MEDIA_ROOT = os.path.join(PROJECT_ROOT, 'site_media', 'media')
MEDIA_URL = '/site_media/media/'
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'site_media', 'static')
SITE_MEDIA_URL = '/site_media/'
STATIC_URL = '/site_media/'
ADMIN_TOOLS_MEDIA_URL = '/site_media/'
ADMIN_MEDIA_PREFIX = posixpath.join(STATIC_URL, "admin/")
STATICFILES_DIRS = (os.path.join(PROJECT_ROOT, 'site_media'),)

urls.py

if settings.SERVE_MEDIA:
    urlpatterns += patterns("",
        (r'^site_media/(?P<path>.*)$', 'django.views.static.serve',
            {'document_root': settings.STATIC_ROOT, 'show_indexes': True }),
        (r'^static/(?P<path>.*)$', 'django.views.static.serve',
            {'document_root': settings.STATIC_ROOT, }),

models.py

image = ImageField(upload_to='products/product_type', blank=True, null=True)

template (simplified)

<img src="{{object.image.url}}" >

Add following line under if settings.DEBUG in urls.py

(r'^site-media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, 'show_indexes':True}),

Or set MEDIA_URL = "/media/"

staticfiles serves static files, for media file, you have to specify serving path explicitly.

update

When using file backend to store media files, for example ImageField(upload_to='product'), a file named foo will be created in MEDIA_ROOT/product/foo; The URL of the file in page is MEDIA_URL/product/foo; On development server, you have to config urls.py to serve request for 'MEDIA_URL/(?<path>.*)$', inside which the path is product/foo.

Sumit Jha

Inside your urls.py file, you need to do:

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


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

The url pattern is not consistent with your MEDIA_URL. You can change the MEDIA_URL in your settings to "/media/" to match your urls setting.

I think this is true and okey

(r'^site-media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': 'media/your/path'}),

after that check your file exists in this path

mean you must has products/co_macysLogo3.gif in media path

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!