2
votes

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'))
1
You might want to take a look at this answer which weights pros and cons of different solutions: stackoverflow.com/a/7934577/497056Ivan Kharlamov

1 Answers

1
votes

You want to override the __init__ method like you did with the save method, and call self.get_thumbs() before you call super(Photo, self).init(*args, **kwargs)

Alternately, you could look at other peoples solution to this problem sorl.thumbnail, django-imagekit, or easy-thumbnails (which is sort of like a combination of the two)