A
A
Andrey Kovalchuk2017-02-08 15:06:59
Django
Andrey Kovalchuk, 2017-02-08 15:06:59

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

2 answer(s)
U
un1t, 2017-02-08
@mrkovalchuk

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()

A
Andrey Kovalchuk, 2017-02-13
@mrkovalchuk

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)

We get the response, extract the name of the image, create a BytesIO object, extract the content and write it to the buffer, then we take our object (the scrapy item created with django-item) and convert it to the desired format, passing the buffer and the title. Then just save the item\object news.save(
) we were missing a name for the file

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question