You're probably using an ImageField.
from django.db import models
class ExampleModel(models.Model):
image = models.ImageField(
'Image',
upload_to='images/'
)
You should swap it out</model_integration>
for a VersatileImageField
. It's better!
from django.db import models
from versatileimagefield.fields import VersatileImageField
class ExampleModel(models.Model):
image = VersatileImageField(
'Image',
upload_to='images/'
)
Out-of-the-box, VersatileImageField
provides the same functionality as ImageField
:
Template Code | Image |
---|---|
<img src="{{ instance.image.url }}" /> |
So what sets it apart?
A VersatileImageField
can create new images on-demand both in templates and the shell.
Let's make a thumbnail image that would fit within a 200px by 200px area:
Template Code | Image |
---|---|
<img src="{{ instance.image.thumbnail.200x200 }}" /> |
No crufty templatetags necessary! Here's how you'd do the same in the shell:
>>> from someapp.models import ExampleModel
>>> img = ExampleModel.objects.get()
>>> img.image.thumbnail['200x200'].url
'/media/__sized__/images/test-image-thumbnail-200x200.jpg'
>>> img.image.thumbnail['200x200'].name
'__sized__/images/test-image-thumbnail-200x200.jpg'
You can use it to create cropped images, too:
Template Code | Default, Absolutely Centered Crop |
---|---|
<img src="{{ instance.image.crop.400x400 }}" /> |
Uh-oh. That looks weird.
Don't worry! VersatileImageField
ships with a handy admin-compatible widget that you can use to specify an image's Primary Point of Interest (PPOI)</specifying_ppoi>
by clicking on it.
Note the translucent red square underneath the mouse cursor in the image within the left column below:
Admin Widget PPOI Selection Tool | Resultant Cropped Image |
---|---|
Ahhhhh, that's better.
VersatileImageField
has filters <filters>
, too! Let's create an inverted image:
Template Code | Image |
---|---|
<img src="{{ instance.image.filters.invert.url }}" /> |
You can chain filters and sizers together:
Template Code | Image |
---|---|
<img src="{{ instance.image.filters.invert.thumbnail.200x200 }}" /> |
Making new sizers and filters (or overriding existing ones) is super-easy via the Sizer and Filter framework </writing_custom_sizers_and_filters>
.
If you've got an API powered by Django REST Framework you can use VersatileImageField
to serve multiple images (in any number of sizes and renditions) from a single field. Learn more here </drf_integration>
.
VersatileImageField
's on-demand image creation provides maximum flexibility during development but can be easily turned off </improving_performance>
so your app performs like a champ in production.
django-versatileimagefield
is a rock solid, fully-tested Django app that is compatible with Python 2.7, 3.3 and 3.4 and works with Django 1.6.x thru 1.8.x
You should totally try it out </installation>
! It's 100% backwards compatible with ImageField
so you've got nothing to lose!