My application needs to save multiple versions of an uploaded Image. One high quality image and another one just for thumbnails use (low quality). Currently this is working most of the time but sometimes the save method simply fails and all of my Thumbnail images are getting deleted, especially then if I use the remove_cover checkbox at my form
raise ValueError("The '%s' attribute has no file associated with it." % self.field.name) app | ValueError: The 'postcover_tn' attribute has no file associated with it.
-> See full trace here: https://pastebin.com/hgieMGet
models.py
class Post(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
author = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField()
content = models.TextField(blank=False)
postcover = models.ImageField(
verbose_name="Post Cover",
blank=True,
null=True,
upload_to=image_uploads,
)
postcover_tn = models.ImageField(
verbose_name="Post Cover Thumbnail",
blank=True,
null=True,
upload_to=image_uploads,
)
published_date = models.DateTimeField(auto_now_add=True, null=True)
def save(self, *args, **kwargs):
super(Post, self).save(*args, **kwargs)
if self.postcover:
if not (self.postcover_tn and os.path.exists(self.postcover_tn.path)):
image = Image.open(self.postcover)
outputIoStream = BytesIO()
baseheight = 500
hpercent = baseheight / image.size[1]
wsize = int(image.size[0] * hpercent)
imageTemproaryResized = image.resize((wsize, baseheight))
imageTemproaryResized.save(outputIoStream, format='PNG')
outputIoStream.seek(0)
self.postcover = InMemoryUploadedFile(outputIoStream, 'ImageField',
"%s.png" % self.postcover.name.split('.')[0], 'image/png',
sys.getsizeof(outputIoStream), None)
image = Image.open(self.postcover)
outputIoStream = BytesIO()
baseheight = 175
hpercent = baseheight / image.size[1]
wsize = int(image.size[0] * hpercent)
imageTemproaryResized = image.resize((wsize, baseheight))
imageTemproaryResized.save(outputIoStream, format='PNG')
outputIoStream.seek(0)
self.postcover_tn = InMemoryUploadedFile(outputIoStream, 'ImageField',
"%s.png" % self.postcover.name.split('.')[0], 'image/png',
sys.getsizeof(outputIoStream), None)
elif self.postcover_tn:
self.postcover_tn.delete()
super(Post, self).save(*args, **kwargs)
It also seems that I'm not able to properly resolve:
- self.postcover_tn.delete() -> Unresolved attribute reference 'delete' for class 'InMemoryUploadedFile'
- self.postcover_tn.path -> Unresolved attribute reference 'path' for class 'InMemoryUploadedFile'
forms.py:
def save(self, commit=True):
instance = super(PostForm, self).save(commit=False)
if self.cleaned_data.get('remove_cover'):
try:
os.unlink(instance.postcover.path)
except OSError:
pass
instance.postcover = None
if commit:
instance.save()
return instance
ImageField
. This way you don't need to worry about resizing and save errors.