【问题标题】:Save downloaded image in django ImageField将下载的图像保存在 django ImageField 中
【发布时间】:2018-01-01 23:32:59
【问题描述】:

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

现在我收到此错误:

'照片没有内容。'

怎么了?

【问题讨论】:

标签: python django urllib


【解决方案1】:

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

你应该:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-24
    • 1970-01-01
    • 2011-12-15
    • 2018-08-10
    • 2013-02-13
    • 2016-04-23
    • 2012-02-08
    相关资源
    最近更新 更多