Search code examples
djangodjango-modelssorl-thumbnail

sorl-thumbnail ImageField dynamic upload_to path


I know theres a way to dynamic upload path in django ImageFields and FileFields, which is to pass a upload_to=callable in the field, but is there a way to achieve this with sorl-thumbnail ImageField?

This is my model.py, Im getting a upload_path not defined!

class Brand(models.Model):
    title = models.CharField(max_length=255, null=True, blank=True)
    photo = sorl.thumbnail.ImageField(upload_to=upload_path)
    external = models.BooleanField(_('External Brand? ("Key Account")?'))

    def upload_path(self):
        return u'%s' % self.title

Solution

  • See this related SO question.

    Sorl-thumbnail doesn't do anything special with upload_to. It merely punts the handling of passed arguments via inheriting from Django's FileField, so anything that works with a standard FileField or ImageField will work with sorl-thumbnail's ImageField as well.

    I think your problem is defining the method on the model. Every implementation I've ever seen or done myself has the method being outside the model. Django automatically passes in the instance to the method, so that's how you access the data on the model -- not through self.