django上傳圖片


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庫,對圖片進行各種操作----參考資料:廖雪峰--PILPIL官方文檔

我使用的功能簡單,只是保存圖片而已。代碼:

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.username

 html代碼

<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

 

 

============如有錯誤歡迎指正,轉載請注明出處==============

  






免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM