【Django】上传图片之路径问题
2015-08-17 06:03
686 查看
问题描述
在debug模式下,访问路径「http://127.0.0.1/media/images/logo.png」出现404错误。
而不是预想中可以显示到图片。
(如果想要显示图片,则需要将图片放到某个app下的media/images目录下,即
http://127.0.0.1/myapp/images/logo.png,这显然和我们的预期目的不符)
配置
在settings.py中设置:
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
MEDIA_URL = '/media/'
在
models.py中设置
id_front_image = models.ImageField(upload_to='.', max_length=255, null=True, blank=True)
结果
图片可以得到正确的存放路径。/home/lou/mysite/media/logo.png
但是在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)
相关文章推荐
- Django(下)
- GO语言做文件服务器小总结
- django_学习笔记0816
- POJ2007--Scrambled Polygon
- hdu 4983 Goffi and GCD(欧拉函数)
- Beanstalkd的使用(Golang)
- NYOJ 635 Oh, my goddess (简单BFS)
- Django(中)
- POJ 2195 D - Going Home 费用流
- GoAgent下local文件下proxy.ini文件各项参数介绍
- 如何直接从 Google Play 下载 APK 文件?
- 如何用Go语言打造一个高性能MySQL Proxy
- [Machine Learning & Algorithm] 决策树与迭代决策树(GBDT)
- 如何用Go语言打造一个高性能MySQL Proxy
- Google APAC 2016 University Graduates Test Practice Round APAC test
- django-rest-framework指南(3):Class Based Views(类视图)
- Google APAC 2016 University Graduates Test(google校招笔试)
- Google笔试(2015年8月)
- Codeforces Round #313 (Div. 2)-Gerald's Hexagon 找规律-几何规律-
- HDU_1847 Good Luck in CET-4 Everybody!(SG函数)