Amin Ba
Amin Ba

Reputation: 2436

UnicodeDecodeError: when trying to save image to the django model

I have this model:

class MyModel(Model):

    other_field = CharField(max_length=200)
    image = ImageField(upload_to='images/', null=True, blank=True, )

I enter into the shell

Python manage.py shell

Then:

import os
from django.core.files import File

my_image1_path = 'C:\\Users\\Amin\\PycharmProjects\\myproject\\myimage1.png'
my_image1_file = File(open(my_image1_path ))
from myapp.models import MyModel
model_ins = MyModel.objects.get(id=1)
model_ins.image.save('myimage1.png', my_image1_file )

I encounter this error:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte

I have another ins in my model and I encounter no error with that other image file:

import os
from django.core.files import File

import os
from django.core.files import File

my_image1_path = 'C:\\Users\\Amin\\PycharmProjects\\myproject\\myimage2.svg'
my_image1_file = File(open(my_image2_path ))
from myapp.models import MyModel
model_ins = MyModel.objects.get(id=2)
model_ins.image.save('myimage2.svg', my_image2_file ) 

Any clue what is the problem with the image1?!

Upvotes: 1

Views: 81

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476699

The problem is that open will open the file as text by default, not as a binary stream.

You thus can open it by setting the mode to 'rb':

with open(my_image1_path, 'rb') as f:
    my_image1_file = File(f)

Make use of a context manager (the with block), to ensure that the file is closed properly.

Upvotes: 1

Related Questions