Cant upload Image though manage.py shell

Hi everyone

So i have no idea why this is happening, maybe some error in the filename, here are my codes.

Views File:

class unique_colors(models.Model):

	color_name = models.CharField(max_length=300,unique=True)

	color_image = ResizedImageField(size=[50, 50], quality=100, upload_to= "color_images")

My mange.py shell Code:

import os
from natsort import natsorted
from django.core.files import File

for s in natsorted(os.listdir("color_images")):
 color_name = os.path.splitext(s)[0]
 K = unique_colors(color_name = color_name)
 K.color_image.save(f'{color_name}.jpg', File(open(os.path.join('color_images',s), 'rb')))

Error Code:

UnidentifiedImageError                    Traceback (most recent call last)
<ipython-input-10-5dbe1a8e331b> in <module>
      2     color_name = os.path.splitext(s)[0]
      3     K = unique_colors(color_name = color_name)
----> 4     K.color_image.save(f'{color_name}.jpg', File(open(os.path.join('color_images',s), 'rb')))
      5 

~/.local/lib/python3.9/site-packages/django_resized/forms.py in save(self, name, content, save)
     61     def save(self, name, content, save=True):
     62         content.file.seek(0)
---> 63         img = Image.open(content.file)
     64 
     65         if DEFAULT_NORMALIZE_ROTATION:

~/.local/lib/python3.9/site-packages/PIL/Image.py in open(fp, mode, formats)
   2956     for message in accept_warnings:
   2957         warnings.warn(message)
-> 2958     raise UnidentifiedImageError(
   2959         "cannot identify image file %r" % (filename if filename else fp)
   2960     )

UnidentifiedImageError: cannot identify image file <_io.BufferedReader name='color_images/Abbey.jpg'>

Try assigning the file field object to a SimpleUploadedFile and then call save on the model instance

1 Like

thanks a lot it worked :slight_smile:

1 Like

As far as I could tell, there wasn’t an example in the documentation so I made a PR to add one.