Reputation: 64853
having a similar model:
class Foo(models.Model):
slug = models.SlugField(unique=True)
img = ImageWithThumbnailsField(upload_to='uploads/',thumbnail={'size': (56, 34)})
It works fine but I want to add 2 more features to it:
1- It should also generate a second thumbnail sized 195x123, in addition to 56x34
2- While saving the model original image and it's two thumbnails should be renamed as by using the slug.
For instance
I am uploading 1.jpg and I name slug as "i-like-this-country2" I should save these named versions should be saved:
1- i-like-this-country2_original.jpg
2- i-like-this-country2_middle.jpg #for 195x123
3- i-like-this-country2_small.jpg #for 56x34
Upvotes: 0
Views: 704
Reputation: 3586
All you have to do is to create a method in your models.py like this:
def rename_file(instance, filename):
extension = filename.split(".")[1]
rename = "rename_here"
return rename + "." + extension
Then in the class that extends models.Model
class MyImage(models.Model):
image = ImageField(upload_to=rename_file)
Don't forget to import from sorl.thumbnail import ImageField
too!
Upvotes: 0
Reputation: 19495
First part:
Just pass it in like this: sizes=( (56,34), (195,123), )
Second part:
You can specify a function for the upload_to
which Django will call, passing it an instance of the model and the original filename. With that, you can put together a function that renames the file based on the slug because Django will use whatever you return it instead. Untested code, but something like this:
def _Foo_img_name(instance, filename):
# grab the extension
left_path, extension = self.file.name.rsplit('.',1)
# change the filename then return
return 'uploads/%s.%s' % (instance.slug, extension)
class Foo(models.Model):
img = ImageWithThumbnailsField(upload_to=_Foo_img_name, ... )
I don't believe you can do is change the <filename>_56x34.jpg
into anything but that.
Upvotes: 3