Skip to content

3rd package

Creating image thumbnails using easy-thumbnails

We are displaying the original image on the detail page, but dimensions for different images may vary considerably. The file size for some images may be very large, and loading them might take too long.

The best way to display optimized images in a uniform manner is to generate thumbnails. A thumbnail is a small image representation of a larger image. Thumbnails will load faster in the browser and are a great way to homogenize images of very different sizes. We will use a Django application called easy-thumbnails to generate thumbnails for the images bookmarked by users.

pip install easy-thumbnails==2.8.1
INSTALLED_APPS = [
    # ...
    'easy_thumbnails',
]

The easy-thumbnails application offers you different ways to define image thumbnails. The application provides a {% thumbnail %} template tag to generate thumbnails in templates and a custom ImageField if you want to define thumbnails in your models. Let’s use the template tag approach.

Edit the images/image/detail.html template and consider the following line:

<img src="{{ image.image.url }}" class="image-detail">

The following lines should replace the preceding one:

{% load thumbnail %}

<a href="{{ image.image.url }}">
    <img src="{% thumbnail image.image 300x0 %}" class="image-detail">
</a>

We have defined a thumbnail with a fixed width of 300 pixels and a flexible height to maintain the aspect ratio by using the value 0. The first time a user loads this page, a thumbnail image will be created. The thumbnail is stored in the same directory as the original file. The location is defined by the MEDIA_ROOT setting and the upload_to attribute of the image field of the Image model. The generated thumbnail will then be served in the following requests.


The original filename is followed by additional details of the settings used to create the thumbnail. For a JPEG image, you will see a filename like filename.jpg.300x0_q85.jpg, where 300x0 are the size parameters used to generate the thumbnail, and 85 is the value for the default JPEG quality used by the library to generate the thumbnail.

You can use a different quality value using the quality parameter. To set the highest JPEG quality, you can use the value 100, like this: {% thumbnail image.image 300x0 quality=100 %}. A higher quality will imply a larger file size.

The easy-thumbnails application offers several options to customize your thumbnails, including cropping algorithms and different effects that can be applied. If you run into any issues generating thumbnails, you can add THUMBNAIL_DEBUG = True to the settings.py file to obtain the debug information. You can read the full documentation of easy-thumbnails at easy-thumbnails.readthedocs.io.


Adding the tagging functionality

A very common functionality in blogs is to categorize posts using tags. Tags allow you to categorize content in a non-hierarchical manner, using simple keywords. A tag is simply a label or keyword that can be assigned to posts. We will create a tagging system by integrating a third-party Django tagging application into the project.

django-taggit is a reusable application that primarily offers you a Tag model and a manager to easily add tags to any model. You can take a look at its source code at https://github.com/jazzband/django-taggit.

First, you need to install django-taggit via pip by running the following command:

pip install django-taggit==3.0.0

Then, open the settings.py file of the mysite project and add taggit to your INSTALLED_APPS setting, as follows:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'blog.apps.BlogConfig',
    'taggit',
]

Open the models.py file of your blog application and add the TaggableManager manager provided by django-taggit to the Post model using the following code:

from taggit.managers import TaggableManager

class Post(models.Model):
    # ...
    tags = TaggableManager()

The tags manager will allow you to add, retrieve, and remove tags from Post objects.

The Tag model is used to store tags. It contains a name and a slug field.

Creating custom template tags and filters

Django provides the following helper functions that allow you to easily create template tags:

  • simple_tag: Processes the given data and returns a string
  • inclusion_tag: Processes the given data and returns a rendered template

Template tags must live inside Django applications.

Cleaning form fields

forms.py
def clean_url(self):
    url = self.cleaned_data['url']
    valid_extensions = ['jpg', 'jpeg', 'png']
    extension = url.rsplit('.', 1)[1].lower()
    if extension not in valid_extensions:
        raise forms.ValidationError('The given URL does not match valid image extensions.')
    return url

Reference

  • [Django 4 by example: pg-265]