1
votes

Foo (models.Model): slug = models.SlugField(unique=True) image = models.ImageField(upload_to='uploads/')

I want to do two things with this:

First of all, I want my image to be forced to resize to a specific width and height after the upload. I have tried this reading the documentation but seems to getting error:

image = models.ImageField(upload_to='uploads/', height_field=258, width_field=425)

Secondly, when adding an item via admin panel, I want my image's file name to be renamed as same as slug, if any issue arises (like if such named image already exists, add "_" to the end as it used to do. IE: My slug is i-love-you-guys , uploaded image such have i-love-you-guys.png at the end.

1

1 Answers

2
votes

Signals are the answer to both of your questions.

As stated in the docs, the height_field and width_field are names of fields where to store the original image's height and width -- not to coerce the image to a certain size. I think the best way to handle what you want to do is to use either the pre_save or post_save signal to resize the image using PIL. You may also want to check out sorl. In fact, you can use the sorl's thumbnail in your signal to create the new image.

To rename the filename, also use a signal.