AttributeError : type object '_io.StringIO' has no attribute 'StringIO'

AttributeError : type object '_io.StringIO' has no attribute 'StringIO'

在我的模型中,我想通过覆盖保存方法来格式化图像字段

我已经在我的模型中这样做了

from PIL import Image as Img
from io import StringIO
from django.core.files.uploadedfile import InMemoryUploadedFile


class Blog(models.Model):
    Blog_image= models.ImageField(upload_to="...", blank=True)

    def save(self, *args, **kwargs):
    if self.Blog_image:
        image = Img.open(StringIO.StringIO(self.Blog_image.read()))
        image.thumbnail((900,300), Img.ANTIALIAS)
        output = StringIO.StringIO()
        image.save(output, format='JPEG', quality=150)
        output.seek(0)
        self.Blog_image = InMemoryUploadedFile(output,'ImageField', "%s.jpg" %self.Blog_image.name, 'image/jpeg', output.len, None)
    super(Blog, self).save(*args, **kwargs)

但是得到这个属性错误

AttributeError : type object '_io.StringIO' has no attribute 'StringIO'

谁能解释我为什么会收到这个错误???

我的python版本是3.6.4

我的 Django 版本是 2.0.7

找到解决方案 这适用于 Python 3.6.2,但我不知道它保存在哪里以及它从哪个文件夹调用:

from PIL import Image
from io import BytesIO
from django.core.files.uploadedfile import InMemoryUploadedFile
import sys

    def save(self, *args, **kwargs):
    imageTemproary = Image.open(self.Blog_image)
    outputIoStream = BytesIO()
    imageTemproaryResized = imageTemproary.resize( (900,300) ) 
    imageTemproaryResized.save(outputIoStream , format='JPEG', quality=150)
    outputIoStream.seek(0)
    self.Blog_image = InMemoryUploadedFile(outputIoStream,'ImageField', "%s.jpg" %self.Blog_image.name.split('.')[0], 'image/jpeg', sys.getsizeof(outputIoStream), None)
    super(Blog, self).save(*args, **kwargs)

使用 BytesIO 完成,效果很好

输出=StringIO.StringIO()

改为:

output = StringIO()

您已经导入了 io.StringIO()。