Answer the question
In order to leave comments, you need to log in
How to save image in django ImageField?
Good day.
I have a problem with saving pictures. I think like this: we get a picture, draw a path for it, write it down with a write, reopen the file, assign a file to the field, save it.
It sounds interesting, and even works, but with one amendment: two images will be saved. How to avoid it?
FragmentCode.py
news = NewsItem(**item)
r = requests.get(news['image'])
image_path = MEDIA_ROOT + 'news_image/' + path.basename(urlparse(news['image']).path)
with open(image_path, 'wb') as f:
f.write(r.content)
reopen = open(image_path, 'rb')
django_file = File(reopen)
news['image'] = django_file
Answer the question
In order to leave comments, you need to log in
Well, you save it once through write, and the second time it is saved apparently when you save the model.
NewsItem is a model or what?
And you do not need to save it to disk yourself.
buf = BytesIO()
buf.write(r.content)
# obj это инстанс модели
obj.image = File(buf)
obj.save()
So let's recap. Working option:
news = NewsItem(**item)
r = requests.get(news['image'])
image = path.basename(urlparse(news['image']).path)
buf = BytesIO()
buf.write(r.content)
news['image'] = File(buf, image)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question