Reputation:
In my django app i'm trying to resize & compress an Image before saving it to the database.
Here's how I did it inside the models
class Data(models.Model):
image = models.ImageField(upload_to='all_images/', null=True, blank=True)
def save(self, *args, **kwargs):
if self.image:
img = Image.open(self.image)
resize = img.resize((240, 240), Image.ANTIALIAS)
new_image = BytesIO()
resize.save(new_image, format=img.format, quality=80, save=False)
temp_name = os.path.split(self.image.name)[1]
self.image.save(temp_name, content=ContentFile(new_image.getvalue()), save=False)
super(Data, self).save(*args, **kwargs)
Here's the problem, I saved an image named tesla.jpg
into the database, it compressed & resized it well, but it renamed it something like, tesla_CKBw0Kr_iWKC4Ry_ucPoh4b_BB2C8Ck_WrfWkPR_Tzig2T1_tdhst4b_3Bysn6k_i4ffhPR_yhig2T1.jpg
I'm worried about the new name because normally it should be tesla_CKBw0Kr.jpg
or something smaller, so what's the problem in my code & how can we fix that?
Upvotes: 0
Views: 145
Reputation: 1717
Django mangles the image filename so that you don't run into filename collisions in the filesystem. Consider what if you had to save another image named tesla.jpg
and don't want it to accidentally overwrite the first one.
You don't have to worry about that though. Django stores the real, original filename in the UploadeFile object.
UPDATE
Django will keep adding random characters to the filename if you upload more files with the same filename:
https://github.com/django/django/blob/master/django/core/files/storage.py#L60-L89
If you worry about hitting the filesystem's filename length limit, then set an appropriate max_length on the ImageField. The function will then keep truncating the file_name and generating new names within the filename length limit, until it finds a free name.
Upvotes: 1