2016-03-01 19 views
1

我的問題是,當我嘗試使用Django shell將圖像保存到我的模型時,我得到這個錯誤,我找不到任何解決方案。Django Shell圖片上傳_io.BufferedReader沒有屬性大小

models.py

class AdImage(models.Model): 
    ad = models.ForeignKey(Ad) 
    full_photo = models.ImageField(upload_to='uploads/', blank=True) 

我導入模型創建AdImage實例添加 '廣告',並嘗試

imagead.full_photo.save("NowHiring.jpg",open("C:\\NowHiring.jpg", "rb")) 

,但我得到一個錯誤

Traceback (most recent call last): 
    File "<console>", line 1, in <module> 
    File "C:\Users\hp\Envs\platform\lib\site-packages\django\db\models\fields\file 
s.py", line 106, in save 
    self._size = content.size 
AttributeError: '_io.BufferedReader' object has no attribute 'size' 

使用:的Python 3.5,Django 1.9

我該怎麼辦?

回答

2

FieldFile.save方法需要與django.core.files.File一個實例調用,而不是內置的Python文件句柄。將保存調用更改爲:

from django.core.files import File 

imagead.full_photo.save("NowHiring.jpg", File(open("C:\\NowHiring.jpg", "rb"))) 

Django文檔參考號爲FieldFile.save