I got those two functions in my Model but only the cover_photo one is working.
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, blank=True, null=True)
profile_picture = models.ImageField(upload_to='users/profile_pictures', blank=True, null=True)
cover_photo = models.ImageField(upload_to='users/cover_photos', blank=True, null=True)
...
def save(self, *args, **kwargs):
super().save(*args, **kwargs)
if self.profile_picture:
img = Image.open(self.profile_picture.path)
if img.height > 50 or img.width > 50:
new_height = 100
new_width = int(new_height / img.height * img.width)
img = img.resize((new_width, new_height))
img.save(self.profile_picture.path)
def save(self, *args, **kwargs):
super().save(*args, **kwargs)
if self.cover_photo:
img = Image.open(self.cover_photo.path)
if img.width > 100 or img.height > 100:
new_width = 600
new_height = int(new_width / img.width * img.width)
img = img.resize((new_height, new_width))
img.save(self.cover_photo.path)
If I swap then, only the profile_picture works but the other one stops. Does any one have any idea why this happens? Is there a way to make both works.
you can have only one save method in the class and the 2nd one is always overiding the 1st one. You can put the whole code in one save function:
def save(self, *args, **kwargs):
super().save(*args, **kwargs)
if self.profile_picture:
img = Image.open(self.profile_picture.path)
if img.height > 50 or img.width > 50:
new_height = 100
new_width = int(new_height / img.height * img.width)
img = img.resize((new_width, new_height))
img.save(self.profile_picture.path)
if self.cover_photo:
img = Image.open(self.cover_photo.path)
if img.width > 100 or img.height > 100:
new_width = 600
new_height = int(new_width / img.width * img.width)
img = img.resize((new_height, new_width))
img.save(self.cover_photo.path)