Note that there are some explanatory texts on larger screens.

plurals
  1. PODjango - Saving an image manually to an ImageField field
    primarykey
    data
    text
    <p>The following code takes an image after it gets saved and makes a thumbnail out of it:</p> <pre><code>class Image(models.Model): image = models.ImageField(upload_to='images') thumbnail = models.ImageField(upload_to='images/thumbnails', editable=False) def save(self, *args, **kwargs): super(Image, self).save(*args, **kwargs) if self.image: from PIL import Image as ImageObj from cStringIO import StringIO from django.core.files.uploadedfile import SimpleUploadedFile try: # thumbnail THUMBNAIL_SIZE = (160, 160) # dimensions image = ImageObj.open(self.image) # Convert to RGB if necessary if image.mode not in ('L', 'RGB'): image = image.convert('RGB') # create a thumbnail + use antialiasing for a smoother thumbnail image.thumbnail(THUMBNAIL_SIZE, ImageObj.ANTIALIAS) # fetch image into memory temp_handle = StringIO() image.save(temp_handle, 'png') temp_handle.seek(0) # save it file_name, file_ext = os.path.splitext(self.image.name.rpartition('/')[-1]) suf = SimpleUploadedFile(file_name + file_ext, temp_handle.read(), content_type='image/png') self.thumbnail.save(file_name + '.png', suf, save=False) except ImportError: pass </code></pre> <p>It's working fine, the original image + the thumbnail are both being uploaded, and image is being assigned the correct path.</p> <p>The only problem is thumbnail is not being assigned the path of the newly created thumbnail - it's empty in the database. I have read the documentation, and it looks like if I save the thumbnail with save=True it should fix my problem:</p> <pre><code>self.thumbnail.save(file_name + '.png', suf, save=True) </code></pre> <p>However, doing this is raising the following:</p> <pre><code>Django Version: 1.3.1 Exception Type: IOError Exception Value: cannot identify image file </code></pre> <p>I can't figure out what I'm doing wrong.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload