Search code examples
python-3.xdjangostaticdjango-templateswebp

Django webp converter tag static_webp not working


I installed the webp_converter package at documented Here

{% load webp_converter %}

This is not working which I want to add static_webp
<img src="{% static_webp 'modelImage.url' %}">

This is working fine
<img src="{{ modelImage.url }}">

From Official Doc says
<img src="{% static_webp 'img/hello.jpg' %}">

Solution

  • I could not customize the output to the template using {% static_webp 'modelImage.url' %}. But I was able to convert the file when uploading and store the files immediately in the desired format (webp). My solution may be useful for those who are developing a new project because my method does not assume previously saved files in the model. So let's start in order.

    1. models.py In my model (Catalog) I have overridden the path to where the images are stored by calling the function (rename_file). The function (rename_file) renames the expansion of our file to .webp, creating the correct obj.url . This must be done immediately. Because the obj.url has the attribute read only.

      from django.db import models
      from datetime import date
      
      image_path = os.path.abspath(settings.MEDIA_ROOT + '/photos/asics/' + date.today().strftime('%Y/%m/%d/'))
      
      def rename_file(instance, filename):
          if filename.find('.') >= 0:
              dot_index = (len(filename) - filename.rfind('.', 1)) * (-1)
              filename = filename[0:dot_index]
          filename = '{}.{}'.format(filename, 'webp')
          return os.path.join(image_path, filename)
      
      class Catalog(models.Model):
          photo = models.ImageField(upload_to=rename_file, blank=True)
      
    2. admin.py Images are added to my application through the admin panel. So I decided to convert the images in this file, but it doesn't matter. Here I use signals (post_save) to call the function (convert_image), which converts the image to the desired format (.webp) and replace the Origanal file with a new file.

       from django.contrib import admin
       from .models import Catalog
       from PIL import Image
       from django.db.models.signals import post_save
      
       @receiver(post_save, sender=Catalog)
       def convert_image(instance, **kwargs):
           if image_name:
               im = Image.open(image_name).convert('RGB')
               output_path = str(image_name)
               im.save(output_path, 'webp')
      
        class CatalogAdmin(admin.ModelAdmin):
            def save_model(self, request, obj, form, change):
                global image_name
                image_name = obj.photo
                super().save_model(request, obj, form, change)