Creating image thumbnails using sorl-thumbnail

We are displaying the original image in the detail page but dimensions for different images may vary a lot. Also, the original files for some images might be huge, and loading them might take too long time. The best way to display optimized images in a uniform way is to generate thumbnails. We are going to use a Django application called sorl-thumbnail for this purpose.

Open the terminal and install sorl-thumbnail using the following command:

pip install sorl-thumbnail==12.3

Edit the settings.py file of the bookmarks project and add sorl.thumbnail to the INSTALLED_APPS settings.

Then run the following command to sync the application with your database:

python manage.py migrate

You should see an output that includes the following line:

Creating table thumbnail_kvstore

The sorl-thumbnail 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. We are going to use the template tag approach. Edit the images/image/detail.html template and replace the following line:

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

With these lines:

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

Here, we define a thumbnail with fixed width of of 300 pixels. The first time a user loads this page, a thumbnail image will be created. The generated thumbnail will be served in the following requests. Start the development server with the python manage.py runserver command and access the image detail page for an existing image. The thumbnail will be generated and displayed on the site.

The sorl-thumbnail application offers several options to customize your thumbnails, including cropping algorithms and different effects that can be applied. If you have any difficulty generating thumbnails, you can add THUMBNAIL_DEBUG = True to your settings in order to obtain debug information. You can read the full documentation of the sorl-thumbnail application at http://sorl-thumbnail.readthedocs.org/.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset