Preserve file names with sorl for better SEO

Reading Time : ~ .

We use sorl-thumbnail for scaling images by keeping the original one intact. Sorl proven to be a great tool for generating different sized images throughout the website.

I presume that you know how to use sorl-thumbnail. Here we see how to preserve filename.

Search Engines will give importance to image alt tag content but it definitely has some impact on relevant image file name too.

Sorl will generate random names for the thumbnails it will create and as of now, there is no default setting to preserve filename in generating thumbnails. It is possible to have the same name for different sized images as sorl will create thumbnails in random folders, so, there will be no conflict in names.

Here is the way to achieve that.

We must override the thumbnail backend. So provide

  THUMBNAIL_BACKEND=’SEOThumbnailBackend’

Now we should create the class that returns our custom filenames.

  # thumbnailname.py

  from sorl.thumbnail.base import ThumbnailBackend, EXTENSIONS
  from sorl.thumbnail.conf import settings
  from sorl.thumbnail.helpers import tokey, serialize
  import os.path

  class SEOThumbnailBackend(ThumbnailBackend):

      def _get_thumbnail_filename(self, source, geometry_string, options):
          """
          Computes the destination filename.
          """
          key = tokey(source.key, geometry_string, serialize(options))

          filename, _ext = os.path.splitext(os.path.basename(source.name))

          path = '%s/%s' % (key, filename)
          return '%s%s.%s' % (settings.THUMBNAIL_PREFIX, path, EXTENSIONS[options['format']])

It’s important to keep source key or else there will be an issue of different images with same names, so we should create a folder with source key and save the file with our custom name.

Example:

'micropyramid.png' is stored as THUMBNAIL_PREFIX/source_key/micropyramid.png.

    By Posted On
SENIOR DEVELOPER at MICROPYRAMID

Need any Help in your Project?Let's Talk

Latest Comments
Related Articles
Export html web page to pdf using jspdf Vidyasagar Rudraram

jsPDF is used to generate pdf files in client-side Javascript. You can find the links for jsPDF here and also you can find the link ...

Continue Reading...
Django Generic many to many field implementation Vamsi Popuri

Django application has a GM2MField that combines the features of the standard Django "ManyToManyField" and "GenericForeignKey".

Installation:
pip install django-gm2m

Continue Reading...
Google plus API integration with django Nikhila Mergu

Using GPlus integration, we can get the user verified email id, general information, friends in a less span of time, and user can also share ...

Continue Reading...

Subscribe To our news letter

Subscribe to our news letter to receive latest blog posts into your inbox. Please fill your email address in the below form.
*We don't provide your email contact details to any third parties