Django从url加载图像-反对的ImageField没有属性_committed



我正在使用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 ...

当上面的代码片段运行时,我得到以下错误:

ImageField对象执行属性_committed

我知道这个问题已经被问了好几次了——然而,没有一个公认的答案(我的代码就是基于这个答案(是有效的。我不确定这是否是因为答案已经过时了。

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

获得的原因

ImageField对象执行属性_committed

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

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

为了生成空文件/图像实例,您可以使用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))

最新更新