1

I want to have an image uploaded in the Django admin, resized and with registries on the database before writing to the disk.

Im using Python Imaging Library (PIL)

I was trying this:

from PIL import Image

class Categorias(models.Model):
image_height = models.PositiveIntegerField(editable=False,null=True)
image_width = models.PositiveIntegerField(editable=False,null=True)
the_image = models.ImageField(upload_to="uploads/image/category",width_field="image_width",height_field="image_height")

def save(self):
    if not self.id and not self.the_image:
        return;

    image = Image.open(self.the_image)
    ratio_height = (890*self.image_height)/self.image_width     
    size = (890,ratio_height)
    image = image.resize(size, Image.ANTIALIAS)
    image.save(self.the_image.path)     
    super(Categorias, self).save()

But this was saving the original image and the resized one to the disk, but the resized one has no registries on the database, only the original. And what i want is just a resized image with registries on the database.

So i looked at this article: Save image created via PIL to django model

And im trying this but with no sucess:

def save(self):
    if not self.id and not self.the_image:
        return;

    image = Image.open(self.the_image)
    ratio_height = (890*self.image_height)/self.image_width     
    size = (890,ratio_height)
    tempfile  = image.resize(size, Image.ANTIALIAS)
    tempfile_io =StringIO.StringIO()
    tempfile.save(tempfile_io, format='JPEG')
    image_file = InMemoryUploadedFile(tempfile_io, None, "image.jpg",'image/jpeg',tempfile_io.len, None)
    self.the_image = image.save(self.the_image.path,image_file)
    super(Categorias, self).save()

Im getting the error:

TypeError at /admin/imagens/categorias/add/
__init__() takes exactly 8 arguments (7 given)

Im trying to solve this with no sucess

Full error on: http://pastebin.com/jxia5wPp

The error is trown when i click on save on the admin page.

Community
  • 1
  • 1
Renato Prado
  • 3,770
  • 4
  • 21
  • 26

0 Answers0