-1

quick question. I struggle with writing a conditional in model. If I use code below I get desired .png file, but I'd like to specify that if tripName == 'russia' than do the condition. However when I add that line code goes immediately to the else. Any ideas?

Updated code!

tripImages = (
    ("Russia"),
    ("Italy"),
    ("France"),
)

class Trip(models.Model):

tripName = models.CharField(max_length=64)
tripLogo = models.ImageField(default="default_trip.png", upload_to='trip_pics')

def save(self, *args, **kwargs):
    super().save(*args, **kwargs)

    if self.tripName in tripImages:
        self.tripLogo = '{}.png'.format(self.tripName.lower())
    else:
        pass

    tripImg = Image.open(self.tripLogo)
    print(self.tripLogo)


    if tripImg.height > 300 or tripImg.width > 300:
        output_size = (300, 300)
        tripImg.thumbnail(output_size)
        tripImg.save()

Here is my code print is added whether this function does anything, and it seems that yes. The name is changed, but the image is not swapped. Any ideas?

Hiddenguy
  • 547
  • 13
  • 33

2 Answers2

2

I would suggest that you implement this condition by overriding the save() method for the Django model.

Check this stackoverflow answer

Well to make it little more straightforward

class Trip(models.Model):

tripName = models.CharField(max_length=64)
    tripLogo = models.ImageField(upload_to='trip_pics')

def save(self, *args, **kwargs):
    tripName = getattr(self, 'tripName')
    if tripName in tripImages:
        self.tripLogo = "{}.png".format(tripName.lower())
    else:
        self.tripLogo = "default_trip" 
    super(Model, self).save(*args, **kwargs)
Manu mathew
  • 859
  • 8
  • 25
  • Thanks for the comment, but it doesn't seem to be helpful to me. Or maybe I just have no idea how to use these clues. – Hiddenguy May 10 '19 at 12:47
  • @Hiddenguy I have added more details to the answer. Let me know if that gives you a better picture. – Manu mathew May 10 '19 at 13:01
0

How do you test that the name is changed? You have to be sure about that otherwise the if block will be skipped.

user10547
  • 31
  • 2