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:
class ImageModel(models.Model):
image = models.ImageField(_('image'),
max_length=IMAGE_FIELD_MAX_LENGTH,
upload_to=get_storage_path)
# ...
class Foo(ImageModel):
# ...
# ...
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?
The reason you are getting
ImageField object does attribute _committed
is because the ImageField returns varchar string, not the file instances.
FileField instances are created in your database as varchar columns with a default max length of 100 characters. As with other fields, you can change the maximum length using the max_length argument. doc
For generating an empty file/image instances you can use 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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With