#Saving ImageField with existing File on Disk Fails

9 messages · Page 1 of 1 (latest)

trail maple
#

Hi there I am trying to save a Model with a ImageField

profile_image_path = os.path.join(settings.PROFILE_IMAGES_PATH, f'temp_profile_image_generated.png')
profile_image.resize((150, 150))
profile_image.save(profile_image_path)

with open(profile_image_path, 'r') as f:
    userprofile.avatar = ImageFile(f)
    userprofile.save()

I get that the FileSystem now tries to write the temp file to the actual file.
It creates the destination file on disk.
I have set upload_to and that also works as the file is created.

But then when it tries to read the .png I get a charmap error.
'charmap' codec can't decode byte
Is there a way to create the ImageFile without it trying to copy the content. (The charmap error seems to be a python problem with reading pngs although I can't find anything online)
I saw this code

if hasattr(content, "temporary_file_path"):
  file_move_safe(content.temporary_file_path(), full_path)

But I don't know how to use this "temporary_file_path"

Thanks :)

latent sequoia
trail maple
#

@latent sequoia
that sadly does not work, now it tells me the utf8 codec cant decode
I don't get why the read method tries to decode a raw file.
Could the magic bytes be corrupted, but IDE and Windows open the file in a Image Viewer and it is a valid png file.

latent sequoia
#

perhaps your database connection insists on encoding strings in some coding that doesn't handle all characters 🤷

#

can't tell

#

maybe with open(profile_image_path, 'rb')

#

if it's a PNG file, you shouldn't be trying to decode it into a string, and without the b, that's exactly what you're doing

trail maple
#

oh man

#

I thought that are just read or write flags
Thanks now it works