我正在尝试通过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模式?
任何建议都很感谢。
谢谢。
发布于 2011-04-02 03:42:47
Django >= 1.7的更新
根据Django2.1文档:Serving files uploaded by a user during development
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)
你不再需要if settings.DEBUG
,因为Django会确保它只在调试模式下使用。
Django <= 1.6的原始答案
试着把这个放到你的urls.py里
from django.conf import settings
# ... your normal urlpatterns here
if settings.DEBUG:
# static files (images, css, javascript, etc.)
urlpatterns += patterns('',
(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT}))
有了这个,你可以在DEBUG = True
(当你在本地计算机上运行)时从Django提供静态媒体,但当你进入生产和DEBUG = False
时,你可以让你的web服务器配置提供静态媒体
发布于 2013-04-30 22:51:48
请仔细阅读官方的Django DOC,你会找到最合适的答案。
解决这个问题的最好、最简单的方法如下所示。
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)
发布于 2015-12-23 15:04:39
对于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
https://stackoverflow.com/questions/5517950
复制相似问题