models.py
class Image(models.Model):
title = models.CharField(max_length=255)
image = models.ImageField(upload_to=\'attack_images\', blank=True, null=
When working with ImageField
or FileField
you actually operate on instance of FieldFile
And error in this case is assigning wrong type to ImageField
- it expects FieldFile or at least File type.
Brief answer what can be used instead of self.image = ....
in your code:
from django.core.files import File
...
with open(result[0], "rb") as downloaded_file:
self.image.save(os.path.basename(self.source_url), File(downloaded_file), save=False)
...
Check this StackOverflow answer on saving files. I added a small change - save=False
- while saving image - at this step we only save downloaded file = copying it from temporary path, where it was downloaded by urllib to desired target path in MEDIA
, but not saving model instance.
self.image.save(name, file)
- file is read and saved in MEDIA
at upload_to
path with name name
and model instance is saved aftewards (default save=True).
self.image.save(name, file, save=False)
- the same, but model instance is not saved after the file has been altered, which is probably desired as you save model instance super().save()
later.
What steps are happening in your code: