2013-12-14 146 views

回答

2

matplotlib.pyplot.savefig接受文件類對象作爲第一個參數。你可以通過StringIO/BytesIO(根據你的python版本)。

f = StringIO() 
plt.savefig(f) 

然後,使用django.core.files.ContentFile的字符串轉換爲django.core.files.File(因爲FieldFile.save只接受接受django.core.files.File一個實例)。

content_file = ContentFile(f.getvalue()) 
model_object = Model(....) 
model_object.image_field.save('name_of_image', content_file) 
model_object.save() 
+0

我使用Python 2.7版,我得到一個'不defined'錯誤都StringIO的和BytesIO –

+0

@AswinMurugesh,將其導入。 '從io import BytesIO' /'從StringIO import StringIO' /'從cStringIO import StringIO'。 – falsetru

+0

@AswinMurugesh,http://docs.python.org/2/library/stringio.html/ http://docs.python.org/3/library/io.html#io.BytesIO – falsetru