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

时间:2018-01-01 23:33:00

标签: python django urllib

我想下载图片并保存为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)

更新

我在@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")

现在我收到了这个错误:

  

'照片没有内容。'

有什么问题?

1 个答案:

答案 0 :(得分:0)

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

你应该:

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