一般大家都知道django有个很好用的管理后台admin,普通应用这里就不说了,介绍一下他里面的内置实现的文件上传功能
- 首先在model里定义属性:
pic = models.ImageField('图片',upload_to='uploadImages')
- 修改setting.py
MEDIA_ROOT = 'media1001/'
MEDIA_URL = '/webhost_media/'
- 数据库对应实体的表中添加pic字段,属性为文本,这个只是用来保存文件路径的
- 上面配置代表的意思大概是:
上传图片到:web程序目录/media1001/uploadInages/
访问路径为:http://hostname/webhost_media/uploadImages/filename.jpg
- 基本就是这样,大家可以试一下,很方便,页面调用为modelobjname.pic.url
错误及解决:
- framework.product: "pic": To use ImageFields, you need to install the Python Imaging Library. Get it at http://www.pythonware.com/products/pil/ .
解决:安装Python Imaging Library (PIL)
1)下载:
官方:http://www.pythonware.com/products/pil/
直接下载:http://effbot.org/downloads/Imaging-1.1.7.tar.gz
2)运行命令安装:
sudo python setup.py install
- ImageField causing error when rendering with "The Image" attribute has no file associated with it.
解决:调用pic.url时要先判断pic不为空