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

Niladry Kar picture Niladry Kar · Sep 21, 2018 · Viewed 15.8k times · Source

In my model I want to format the imagefield by overridding the save method

I have done this in my model

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)

But getting this Attribute error

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

Can anyone explain me why I am getting this error???

My python version is 3.6.4

My Django version is 2.0.7

Answer

P-DOX picture P-DOX · Oct 2, 2019

output = StringIO.StringIO()

change it to:

output = StringIO()

you have already imported io.StringIO().