I'm totally, completely new to programming, so please forgive what is probably a stupid question, but I've been beating my head on this for the past couple of days.
I have two models, Photos and Thumbnails. I'm trying to come up with an easy, dynamic way to get the thumbnail links for each Photo. I've come up a function that does this (get_thumbs) but I'd like it to run automatically when the model is called (basically so that I get Photo.get_%s_url % thumb.name as soon as the model is available).
Below is my models.py. Any help or nudge in the right direction (even if it's just "google blah") would be greatly appreciated. Thanks.
class Photo(models.Model):
name = models.CharField(max_length=100)
original_image = models.ImageField(upload_to='photos')
caption = models.TextField(null=True, blank=True)
title_slug = models.SlugField(null=True, blank=True, unique=True)
rootfilename = models.CharField(max_length=50, editable=False, blank=True)
num_views = models.PositiveIntegerField(editable=False, default=0)
def __unicode__(self):
return self.name
thumbnails = Thumbnail.objects.all()
def create_thumbs(self):
for thumbnail in self.thumbnails:
fname = (settings.MEDIA_ROOT + self.rootfilename + '_' + thumbnail.name + '.jpg')
if exists(fname):
None
else:
t_img = Image.open(self.original_image.path)
t_fit = ImageOps.fit(t_img, (thumbnail.height,thumbnail.width), Image.ANTIALIAS, 0, (0.5,0.5))
t_fit.save(fname,"JPEG")
def save(self, *args, **kwargs):
self.rootfilename = (self.original_image.name).strip('photos/.jpg')
super(Photo, self).save(*args, **kwargs)
self.create_thumbs()
def get_thumbs(self):
for thumb in self.thumbnails:
setattr(self, ('get_'+thumb.name+'_url'), ('thumbs/'+self.rootfilename+'_'+thumb.name+'.jpg'))