I am using Django 3.2
I am trying to programatically create a model Foo that contains an ImageField object, when passed an image URL.
This is my code:
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):
# ...
code attempting to create a Foo object from a passed in photo URL
# ...
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
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?
from Django loading image from url - ImageField objected has no attribute _committed
No comments:
Post a Comment