django上传图片
2016-04-15 21:11
405 查看
django修改头像的功能...1.在表单中加入enctype="multipart/form-data;关于表单中enctype的介绍:http://www.w3school.com.cn/tags/att_form_enctype.asp处理表单的视图会在request中接受到上传文件的数据。FILES是个字典,它包含每个FileField的键(或者ImageField,FileField的子类)。这样的话就可以用request.FILES['File']来存放表单中的这些数据了。注意request.FILES只有在请求方法为POST,并且发送请求的<form>拥有enctype="multipart/form-data属性时,才会包含数据。否则request.FILES为空
如下图所示:提交后显示图片信息:如果不加enctype="multipart/form-data:得不到图片信息,只有路径2.上传图片由于model中photo字段存储的是路径,所以首先要把图片保存在图片对应的文件夹下。保存图片中使用到了PIL库,对图片进行各种操作----参考资料:廖雪峰--PIL;PIL官方文档我使用的功能简单,只是保存图片而已。代码:
如下图所示:提交后显示图片信息:如果不加enctype="multipart/form-data:得不到图片信息,只有路径2.上传图片由于model中photo字段存储的是路径,所以首先要把图片保存在图片对应的文件夹下。保存图片中使用到了PIL库,对图片进行各种操作----参考资料:廖雪峰--PIL;PIL官方文档我使用的功能简单,只是保存图片而已。代码:
photo=request.FILES['photo'] if photo: phototime= request.user.username+str(time.time()).split('.')[0] photo_last=str(photo).split('.')[-1] photoname='photos/%s.%s'%(phototime,photo_last) img=Image.open(photo) img.save('media/'+photoname)3.将图片路径更新到数据库调用update()方法即可。注:update()方法对于任何结果集(QuerySet)均有效。通过get()方法的到的不是QuerySet,所以,不可以update,另外get()方法达不到数据和返回条数大于1条的时候都会报错。
print type( UserInfo.objects.get(id=userinfo_id)) ---> <class 'Account.models.UserInfo'> print type( UserInfo.objects.filter(id=userinfo_id))----> <class 'django.db.models.query.QuerySet'>
相关代码如下: models.py
class UserInfo(models.Model): user=models.OneToOneField(User) photo=models.ImageField(upload_to='photos',default='user1.jpg') def __unicode__(self): return self.user.usernamehtml代码
<form action="/updateinfo" method="POST" enctype="multipart/form-data"> <div class="updateImg"> <img src="{{ account.photo.url }}" alt=""/> </div> <input name="photo" type="file" id="exampleInputFile"> <button id="photo" class="btn btn-danger" type="submit">上传头像</button>views.py
def updateInfo(request): if request.method=='POST': photo=request.FILES['photo'] if photo: phototime= request.user.username+str(time.time()).split('.')[0] photo_last=str(photo).split('.')[-1] photoname='photos/%s.%s'%(phototime,photo_last) img=Image.open(photo) img.save('media/'+photoname) count=UserInfo.objects.filter(user=request.user).update( photo=photoname ) if count: # 设置一个session,然后跳转到对应的页面,此处简易写写 return HttpResponse('上传成功') else: return HttpResponse('上传失败') return HttpResponse('图片为空')参考:http://bluecrystal.iteye.com/blog/233030 http://python.usyiyi.cn/django/index.html 廖雪峰--PIL============如有错误欢迎指正,转载请注明出处==============
相关文章推荐
- Manipulator Planning and Obstacle Avoidance Using Genetic Algorithm
- 《Google重新定义公司》
- go语言文件汇总
- Google Play服务中的人脸检测
- django 后端开发思路(1)
- Google Guava之--cache
- golang 走起(七) 多态
- golang 走起(五) Profile 的应用
- 认证模式之Spnego模式
- 认证模式之Spnego模式
- Beego走起(二) 路由的简单设置
- golang优秀实用开源项目收集
- Google Play服务中的条码扫描识别
- Beego走起(一) 初步认识
- BZOJ4281: [ONTAK2015]Związek Harcerstwa Bajtockiego
- beego上传文件
- 堆排序算法及go语言实现
- 归并排序及go语言实现
- golang类型系统笔记
- Go项目目录管理