1.在表单中加入enctype="multipart/form-data;
关于表单中enctype的介绍:
处理表单的视图会在request中接受到上传文件的数据。FILES是个字典,它包含每个FileField的键
(或者ImageField,FileField的子类)。这样的话就可以用request.FILES['File']来存放表单中的这些数据了。
注意request.FILES只有在请求方法为POST,并且发送请求的<form>拥有enctype="multipart/form-data属性时,才会包含数据。否则request.FILES为空
如下图所示:
提交后显示图片信息:
![](http://static.oschina.net/uploads/img/201608/25212214_HM4D.jpg)
如果不加enctype="multipart/form-data:得不到图片信息,只有路径
![](http://static.oschina.net/uploads/img/201608/25212214_7158.jpg)
![](http://static.oschina.net/uploads/img/201608/25212214_96VT.jpg)
2.上传图片
由于model中photo字段存储的是路径,所以首先要把图片保存在图片对应的文件夹下。
保存图片中使用到了PIL库,对图片进行各种操作----参考资料:;
我使用的功能简单,只是保存图片而已。代码:
1 2 3 4 5 6 7 8 | 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)<br><br> img = Image. open (photo) img.save( 'media/' + photoname) |
3.将图片路径更新到数据库
调用update()方法即可。
注:update()方法对于任何结果集(QuerySet)均有效。通过get()方法的到的不是QuerySet,
所以,不可以update,另外get()方法达不到数据和返回条数大于1条的时候都会报错。
1 2 3 | 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
1 2 3 4 5 | class UserInfo(models.Model): user = models.OneToOneField(User) photo = models.ImageField(upload_to = 'photos' ,default = 'user1.jpg' ) def __unicode__( self ): return self .user.username |
html代码
1 2 3 4 5 6 7 | < 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | 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( '图片为空' ) |