django-versatileimagefield
Published May 14, 2024, 5:56 a.m. by cloudblog
Intro
Blog has its own ImageField model field, designed to make it easy to attach an image to your model. Users can upload an image (for example, through the Blog Admin) and it’s stored as a file in the media directory for the project (as defined by the MEDIA_ROOT setting for your project). The ImageField itself just stores a path to the file in the database.
django-versatileimagefield is a library that provides a drop-in replacement for ImageField: VersatileImageField (versatileimagefield.fields.VersatileImageField). It provides helper methods to generate thumbnails, crop images, and apply filters.
Along with VersatileImageField is PPOIField (versatileimagefield.fields.PPOIField), or Primary Point of Interest. This is a field that stores the coordinates of the “point of interest” of the image. If this is set, then when the VersatileImageField crops or thumbnails an image it will center the crop around the primary point of interest instead of the center of the image.
To use an ImageField in a template, we’d access its url attribute. In Blog we’re going to add a photo field to the Post model, so accessing it in a template would be done like this:
<img src="{{ post.photo.url }}"/>
This works the same with a VersatileImageField, but we can also perform cropping like this:
<img src="{{ post.photo.crop.100x100.url }}"/>
Where 100x100 is the size of the cropped image. It will be cropped around the PPOI, if set, otherwise the center of the image. Alternatively, we can thumbnail the image:
<img src="{{ post.photo.thumbnail.100x100.url }}"/>
What’s the difference between cropping and thumbnailing? When the image is cropped, it is cropped to the exact size given. When thumbnailing, it’s resized, not cropped, to fit into the given dimensions. For non-square images, this means that the maximum dimension in our example would be 100 pixels, while the other dimensions would be proportionally smaller.
Try It Out
VersatileImageField sounds pretty straightforward, but we need a couple of adjustments to Blog before we can upload and serve images. We’ll then add the photo and ppoi fields to the Post model.
We’ll start by getting django-versatileimagefield installed, with pip:
pip3 install django-versatileimagefield
Similar posts
There are no similar posts yet.0 comments
There are no comments.