将下载的图像保存在django ImageField中

问题描述 投票:0回答:1

我想下载一张图片并保存为django ImageField。

我的错误在哪里?

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

我在@KapilBarad评论后更改了我的代码:

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

现在我收到这个错误:

“照片没有内容。”

怎么了?

python django urllib
1个回答
0
投票

要将图像保存为Django ImageField,您只需要保存在服务器上的物理文件的路径。

你应该 :

img = Photo()
img.name = "Test"
img.logo("full/path/to/image") # I am assuming logo as ImageField/FileField
img.save()
© www.soinside.com 2019 - 2024. All rights reserved.