我能想出解決辦法。您只需將修改的文件保存爲StringIO
,然後從中創建一個新的InMemoryUploadedFile
。下面是完整的解決方案:
def save(self):
import Image as pil
import StringIO, time, os.path
from django.core.files.uploadedfile import InMemoryUploadedFile
# if avatar is uploaded, we need to scale it
if self.files['avatar']:
# opening file as PIL instance
img = pil.open(self.files['avatar'])
# modifying it
img.thumbnail((150, 150), pil.ANTIALIAS)
# saving it to memory
thumb_io = StringIO.StringIO()
img.save(thumb_io, self.files['avatar'].content_type.split('/')[-1].upper())
# generating name for the new file
new_file_name = str(self.instance.id) +'_avatar_' +\
str(int(time.time())) + \
os.path.splitext(self.instance.avatar.name)[1]
# creating new InMemoryUploadedFile() based on the modified file
file = InMemoryUploadedFile(thumb_io,
u"avatar", # important to specify field name here
new_file_name,
self.files['avatar'].content_type,
thumb_io.len,
None)
# and finally, replacing original InMemoryUploadedFile() with modified one
self.instance.avatar = file
# now, when form will be saved, it will use the modified file, instead of the original
super(UserForm, self).save()