Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 834
Niladry Kar Avatar asked Sep 21 '18 09:09

Niladry Kar


2 Answers

output = StringIO.StringIO()

change it to:

output = StringIO()

you have already imported io.StringIO().

like image 144
P-DOX Avatar answered Nov 15 '22 10:11

P-DOX


Got the solution This works on Python 3.6.2 but I don't know where it was saved and from what folder it calls:

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)

Done it using BytesIO and it worked fine

like image 28
Niladry Kar Avatar answered Nov 15 '22 11:11

Niladry Kar