models.py
class Phrase(models.Model):
image = models.ImageField(blank=True,
default="",
null=False,
upload_to=UploadTo(folder=UPLOAD_TO.VOCABULARY_IMG_FOLDER).save_path)
Script
sample_img_dir = os.path.join(settings.BASE_DIR, 'doc', 'samples', 'img')
sample_images = os.listdir(sample_img_dir)
img = random.choice(sample_images)
f = open(os.path.join(sample_img_dir, img))
sample_img = File(f)
obj = Phrase(
image=sample_img
)
obj.save()
I have a model with an ImageField. I want to fill it with sample data. This is not about testing. I just want to fill the database for development purposes. I saved some 50 jpg files and decided to add them programmatically.
I failed miserably. This code blows up with the exception:
File "/usr/lib/python3.8/codecs.py", line 322, in decode
(result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte
python-BaseException
Process finished with exit code 130 (interrupted by signal 2: SIGINT)
Could you help me?
CodePudding user response:
f = open(os.path.join(sample_img_dir, img), "rb")
should do the trick. If not you can try to add the encoding standard like
f = open(os.path.join(sample_img_dir, img), "rb", encoding="utf-8")
But I'm not sure if this even works with bytes, it might only work for "r"
.
You should give the file also a name:
sample_img = File(f, img)
If you already have the model created you can slo save the file afterwards with:
phrase = Phrase.objects.get(pk=1)
phrase.upload_to.save(img, content=sample_img))
small edit:
you can faster create a new entry with the following command:
phrase = Phrase.objects.create(
image=sample_img
)