【Django】上传图片之路径问题

来源:互联网 发布:西城区2016年经济数据 编辑:程序博客网 时间:2024/06/07 02:41

问题描述

在debug模式下,访问路径「http://127.0.0.1/media/images/logo.png」出现404错误。
而不是预想中可以显示到图片。
(如果想要显示图片,则需要将图片放到某个app下的media/images目录下,即http://127.0.0.1/myapp/images/logo.png,这显然和我们的预期目的不符)

配置

  1. settings.py中设置:

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

  2. models.py中设置

    id_front_image = models.ImageField(upload_to='.', max_length=255, null=True, blank=True)

结果

  1. 图片可以得到正确的存放路径。/home/lou/mysite/media/logo.png
  2. 但是在URL中访问http://127.0.0.1/medias/images/logo.png得到404错误。

解决办法

根据官方文档(https://docs.djangoproject.com/en/1.5/howto/static-files/#serving-files-uploaded-by-a-user)中的说法,有很好的解决办法即在urls.py中添加一段代码:
>

Serving files uploaded by a user¶

During development, you can serve user-uploaded media files from MEDIA_ROOT using thedjango.contrib.staticfiles.views.serve() view. This is not suitable for production use! For some common deployment strategies, see Deploying static files.

For example, if your MEDIA_URL is defined as ‘/media/’, you can do this by adding the following snippet to your urls.py:

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)

福利

当我们在模板(html文件)中引用图片时可以通过下面的方式来轻松获取图片路径:

<img src="{{MEDIA_URL}}/images/logo.png">

参考资料:Django MEDIA_URL and MEDIA_ROOT(http://stackoverflow.com/questions/5517950/django-media-url-and-media-root)

0 0
原创粉丝点击