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
output = StringIO.StringIO()
change it to:
output = StringIO()
you have already imported io.StringIO().
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With