简体   繁体   English

Django 从 url 加载图像 - ImageField objected 没有属性 _committed

[英]Django loading image from url - ImageField objected has no attribute _committed

I am using Django 3.2我正在使用 Django 3.2

I am trying to programatically create a model Foo that contains an ImageField object, when passed an image URL.我正在尝试以编程方式创建一个包含 ImageField object 的 model Foo,当传递图像 URL 时。

This is my code:这是我的代码:

myproject/models.py我的项目/模型.py

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

class Foo(ImageModel):
    # ...

code attempting to create a Foo object from a passed in photo URL试图从传入的照片 URL 创建 Foo object 的代码

# ...

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 ...

When the code snippet above is run, I get the following error:运行上面的代码片段时,我收到以下错误:

ImageField object does attribute _committed ImageField object 确实属性 _committed

I know this question has been asked several times already - however, none of the accepted answers (from which my code is based) - actually works.我知道这个问题已经被问过好几次了——但是,没有一个被接受的答案(我的代码所基于的)——实际上是有效的。 I'm not sure if this is because the answers are old.我不确定这是否是因为答案很旧。

My question therefore is this - how do I fix this error, so that I can load an image from a URL and dynamically create an object that has an ImageField - using the fetched image?因此,我的问题是 - 如何修复此错误,以便我可以从 URL 加载图像并动态创建具有 ImageField 的 object - 使用获取的图像?

The reason you are getting你得到的原因

ImageField object does attribute _committed ImageField object 确实属性 _committed

is because the ImageField returns varchar string, not the file instances.是因为ImageField返回 varchar 字符串,而不是文件实例。

FileField instances are created in your database as varchar columns with a default max length of 100 characters. FileField 实例在您的数据库中创建为 varchar 列,默认最大长度为 100 个字符。 As with other fields, you can change the maximum length using the max_length argument.与其他字段一样,您可以使用 max_length 参数更改最大长度。 doc 文档

For generating an empty file/image instances you can use BytesIO要生成空文件/图像实例,您可以使用BytesIO

Give this a try试试这个

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM