小编smo*_*ele的帖子

PIL 到 Django ImageField

我尝试从 url 创建图像并将其保存在我的 django 模型中。如果第一部分工作正常,我不知道如何将生成的文件关联到我的对象。

这是我生成图像文件的功能:

def get_remote_image(image_url, merchant_product_path):
    im = None
    name = ''
    r = requests.get(image_url, stream=True)
    if r.status_code == 200:
        name = urlparse(image_url).path.split('/')[-1]

        full_path = os.path.join(settings.MEDIA_ROOT, merchant_product_path)
        if not os.path.exists(full_path):
            os.makedirs(full_path)

        im = Image.open(r.raw)
        if im.mode != "RGB":
            im = im.convert("RGB")
        im.thumbnail((500, 500), Image.ANTIALIAS)
        im.save(full_path + name, 'JPEG')

    return {'im': im, 'name': name}
Run Code Online (Sandbox Code Playgroud)

现在,将此文件关联到我的对象的部分:

    i = get_remote_image(row['pict'], m.get_products_media_path())

    obj, created = ProductLine.objects.update_or_create(
    ...
    ...
    ...
    )

if i['im'] is not None:
    try:
        obj.main_picture.save(
            i['name'],
            ContentFile(i['im']),
            save=True)
    except …
Run Code Online (Sandbox Code Playgroud)

python django django-models python-imaging-library

0
推荐指数
1
解决办法
1187
查看次数