Question

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
Was it helpful?

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.

OTHER TIPS

I use this callback with sorl:

def get_image_path(instance, filename):
    """
    puts image in MEDIA_ROOT/photos/instance_id/file
    """
    return os.path.join('photos', str(instance.id), filename)

class Brand(models.Model):
    ...
    photo = sorl.thumbnail.ImageField(upload_to=get_image_path)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top