【问题标题】:Django loading image from url - ImageField objected has no attribute _committedDjango从url加载图像-反对的ImageField没有属性_committed
【发布时间】:2021-05-20 20:08:39
【问题描述】:

我正在使用 Django 3.2

当传递图像 URL 时,我正在尝试以编程方式创建一个包含 ImageField 对象的模型 Foo。

这是我的代码:

myproject/models.py

​​>
class ImageModel(models.Model):
    image = models.ImageField(_('image'),
                              max_length=IMAGE_FIELD_MAX_LENGTH,
                              upload_to=get_storage_path)
    # ...

class Foo(ImageModel):
    # ...

尝试从传入的照片 URL 创建 Foo 对象的代码

# ...

image_content = ContentFile(requests.get(photo_url).content) # NOQA                          
image = ImageField() # empty image

data_dict = {
                'image': image,
                'date_taken': payload['date_taken'],
                'title': payload['title'],
                'caption': payload['caption'],
                'date_added': payload['date_added'],
                'is_public': False  
            }

foo = Foo.objects.create(**data_dict) # <- Barfs here
foo.image.save(str(uuid4()), image_content)
foo.save()  # <- not sure if this save is necessary ...

上面的代码sn-p运行时出现如下错误:

ImageField 对象确实属性 _committed

我知道这个问题已经被问过好几次了——但是,没有一个被接受的答案(我的代码所基于的答案)——实际上是有效的。我不确定这是不是因为答案太旧了。

因此,我的问题是 - 如何修复此错误,以便我可以从 URL 加载图像并动态创建具有 ImageField 的对象 - 使用获取的图像?

【问题讨论】:

    标签: python django django-models


    【解决方案1】:

    你得到的原因

    ImageField 对象确实属性 _committed

    是因为 ImageField 返回 varchar 字符串,而不是文件实例。

    FileField 实例在您的数据库中创建为 varchar 列,默认最大长度为 100 个字符。与其他字段一样,您可以使用 max_length 参数更改最大长度。 doc

    要生成空文件/图像实例,您可以使用BytesIO

    试试这个

    from django.core import files
    from io import BytesIO
    
    url = "https://homepages.cae.wisc.edu/~ece533/images/airplane.png"
    
    io = BytesIO()
    io.write(requests.get(url).content)
    
    foo = Foo()
    foo.caption = payload['caption']
    foo.title = payload['title']
    ...
    
    extention = url.split(".")[-1]
    foo.image.save(f'{str(uuid4())}.{extention}', files.File(io))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-05
      相关资源
      最近更新 更多