0

I want to download an image and save as django ImageField.

Where is my mistake?

from django.core.files import File
from urllib.requests import urlretrieve

from .models import Photo

r = urlretrieve("http://test.com/img/test.png", "./test.png")

f = open("/tmp/test.png", "rb")
django_file = File(f)

img = Photo()
img.name = "Test"
img.logo.save("test.png", django_file, save=True)

UPDATE

I changed my code after @KapilBarad comment:

for url in urls:
    try:
        city = item.city
        title = slugify(item.title)

        request = requests.get(url, stream=True)

        if request.status_code != requests.codes.ok:
            continue

        file_name = url.split('/')[-1]

        lf = tempfile.NamedTemporaryFile()
        for block in request.iter_content(1024 * 8):
            if not block:
                break

            lf.write(block)

        image = Photo()
        image.url = url
        image.image.save('%s/%s/%s' % (city, title, file_name), files.File(lf))

        image.save()

    except Exception as e:
        return JsonResponse({
            "massage": e.args[0]
        }, status=400)

    return HttpResponse(json.dumps({
        "massage": 'All images has been saved.',
    }), content_type="application/json")

Now I get this error:

'Photo has no content.'

What is wrong?

Chalist
  • 3,160
  • 5
  • 39
  • 68
  • Possible duplicate of [Download a remote image and save it to a Django model](https://stackoverflow.com/questions/16174022/download-a-remote-image-and-save-it-to-a-django-model) – Kapil Barad Jan 02 '18 at 07:29
  • @KapilBarad I do everything on the page, but I get error! – Chalist Jan 02 '18 at 14:15

1 Answers1

0

To save the image as Django ImageField you just need the path to physical file saved on your server.

You should :

img = Photo()
img.name = "Test"
img.logo("full/path/to/image") # I am assuming logo as ImageField/FileField
img.save()
Amar
  • 666
  • 5
  • 13