【发布时间】: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