开发者

Django and ImageField Question

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

I want to do two things with this:

Firs开发者_如何学JAVAt 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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜