Django - can't open image in model save()
def upload_path_handler(instance, filename):
return filename
class SpectacleGallery(models.Model):
image = models.ImageField(upload_to=upload_path_handler)
def save(self, *args, **kwargs):
Image.open(self.image)
super(SpectacleGallery, self).save(*args, **kwargs)
When I try to open it I get:
IOError at /admin/index/spectacle/1/
cannot identify image file
Why? File is a proper image. Does that file in save methos is not a good format for PIL?
EDIT: Here's my final working version of code开发者_如何学Go:
def save(self, *args, **kwargs):
# set paths and additional variables
self_pk = self.pk
spectacle_id = self.spectacle_id
spectacle_id_str = str(spectacle_id)
create_gallery_spectacle_dir(spectacle_id)
new_filename = generate_image_name_hash()
new_filename_main = new_filename + '.jpg'
new_filename_thumb = new_filename + '_thumb.jpg'
new_file_thumb_path = settings.SPECTACLE_GALLERY_UPLOAD_DIR + '/' + spectacle_id_str + '/' + new_filename_thumb
new_file_thumb_root_path = settings.SPECTACLE_GALLERY_UPLOAD_PATH + spectacle_id_str + '/' + new_filename_thumb
new_file_root_path = settings.SPECTACLE_GALLERY_UPLOAD_PATH + spectacle_id_str + '/' + new_filename_main
if self.image:
#set new name and thum name
self.image.name = settings.SPECTACLE_GALLERY_UPLOAD_DIR + '/' + spectacle_id_str + '/' + new_filename_main
self.image_thumb = new_file_thumb_path
# image is in form and action is add call the "real" save() method.
if self.image and not self_pk:
super(SpectacleGallery, self).save(*args, **kwargs)
# image is in form and action is edit: get old image info, create variable with image field
if self.image and self_pk:
old_img = SpectacleGallery.objects.get(pk=self.pk)
old_img_instance = old_img.image
if self.image:
if self_pk:
image = old_img_instance
else:
image = self.image
super(SpectacleGallery, self).save(*args, **kwargs) #Call the "real" save() method.
#if image in form
if self.image:
# open file with PIL and convert to RGB
tmp_file = Image.open(self.image.path)
if tmp_file.mode != 'RGB':
tmp_file = tmp_file.convert('RGB')
#create and save thumbnail
tmp_file.thumbnail(settings.SPECTACLE_GALLERY_THUMB_SIZE, Image.ANTIALIAS) #make thumbnail
tmp_file.save(new_file_thumb_root_path, 'JPEG') #save thumbnail
# if edit delete old images
if self_pk:
delete_image_and_thumb(old_img.image, old_img.image_thumb)
#open and resize original image
image = Image.open(self.image.path)
if image.mode != 'RGB':
image = image.convert('RGB')
image.thumbnail(settings.SPECTACLE_GALLERY_IMAGE_SIZE, Image.ANTIALIAS) #make thumbnail
image.save(new_file_root_path,'JPEG', quality=100)
The Django imageField isn't an image you will need to do something like this.
Image.open(self.image.path)
精彩评论