2

If using webp images by default in Django, how would you go about converting the webp images from the database to either png or jpg just on Apple Safari browsers while keeping the default webp for every other browser?

Would Pillow be the way to do this? How would you combine it into the views and the template for loop?

from PIL import Image
image = Image.open("test.webp").convert("RGB")
image.save = ("test.jpg", jpeg)
image.save = ("test.png", png)

Detect User Agent:

https://pypi.org/project/django-user-agents/

Maybe an alternative would be to detect the user agent in the headers?

Would the converted images need to be stored in the project_name/media/ folder (which is where {{ object.thumbnail.url }} currently points to? Or would it go into project_name/static/? Maybe the images could be deleted (cron job maybe) after the Safari session closes or changes to a different view? Not sure the best way to do this.

Code:

HTML:
​
{% for object in object_list %}
<img src="{{ object.thumbnail.url }}" alt="{{ object.thumbnail_alt }}"/>
{% endfor %}
​
​
Models.py:
​
class Course(models.Model):
    thumbnail = models.ImageField(blank=True, null=True, max_length=255)
    thumbnail_alt = models.CharField(blank=True, null=True, max_length=120)
​
​
Views.py:
​
class CourseListView(ListView):
        model = Course
        template_name = 'courses/course_list.html'
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['form'] = self.form
        return context
    def get_queryset(self):
        qs = super().get_queryset()
        self.form = form = CourseForm(self.request.GET)
        #Queries for form go here
        return qs
masuking
  • 61
  • 3

0 Answers0