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

问题描述

在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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值