how to change image format when uploading image in django?

2024/10/5 19:20:42

When a user uploads an image from the Django admin panel, I want to change the image format to '.webp'. I have overridden the save method of the model. Webp file is generated in the media/banner folder but the generated file is not saved in the database. How can I achieve that?

def save(self, *args, **kwargs):super(Banner, self).save(*args, **kwargs)im = Image.open(self.image.path).convert('RGB')name = 'Some File Name with .webp extention' im.save(name, 'webp')self.image = im

But After saving the model, instance of the Image class not saved in the database?

My Model Class is :

class Banner(models.Model):image = models.ImageField(upload_to='banner')device_size = models.CharField(max_length=20, choices=Banner_Device_Choice)
Answer
from django.core.files import ContentFile

If you already have the webp file, read the webp file, put it into the ContentFile() with a buffer (something like io.BytesIO). Then you can proceed to save the ContentFile() object to a model. Do not forget to update the model field, and save the model!

https://docs.djangoproject.com/en/4.1/ref/files/file/

Alternatively

"django-webp-converter is a Django app which straightforwardly converts static images to WebP images, falling back to the original static image for unsupported browsers."

It might have some save capabilities too.

https://django-webp-converter.readthedocs.io/en/latest/

The cause

You are also saving in the wrong order, the correct order to call the super().save() is at the end.

Edited, and tested solution:
from django.core.files import ContentFile
from io import BytesIOdef save(self, *args, **kwargs):#if not self.pk: #Assuming you don't want to do this literally every time an object is saved.img_io = BytesIO()im = Image.open(self.image).convert('RGB')im.save(img_io, format='WEBP')name="this_is_my_webp_file.webp"self.image = ContentFile(img_io.getvalue(), name)super(Banner, self).save(*args, **kwargs) #Not at start  anymore
https://en.xdnf.cn/q/70448.html

Related Q&A

Write info about nodes to a CSV file on the controller (the local)

I have written an Ansible playbook that returns some information from various sources. One of the variables I am saving during a task is the number of records in a certain MySQL database table. I can p…

Python minimize function: passing additional arguments to constraint dictionary

I dont know how to pass additional arguments through the minimize function to the constraint dictionary. I can successfully pass additional arguments to the objective function.Documentation on minimiz…

PyQt5 triggering a paintEvent() with keyPressEvent()

I am trying to learn PyQt vector painting. Currently I am stuck in trying to pass information to paintEvent() method which I guess, should call other methods:I am trying to paint different numbers to a…

A python regex that matches the regional indicator character class

I am using python 2.7.10 on a Mac. Flags in emoji are indicated by a pair of Regional Indicator Symbols. I would like to write a python regex to insert spaces between a string of emoji flags.For exampl…

Importing modules from a sibling directory for use with py.test

I am having problems importing anything into my testing files that I intend to run with py.test.I have a project structure as follows:/ProjectName | |-- /Title | |-- file1.py | |-- file2.py | …

Uploading and processing a csv file in django using ModelForm

I am trying to upload and fetch the data from csv file uploaded by user. I am using the following code. This is my html form (upload_csv1.html):<form action="{% url myapp:upload_csv %}" me…

Plotting Multiple Lines in iPython/pandas Produces Multiple Plots

I am trying to get my head around matplotlibs state machine model, but I am running into an error when trying to plot multiple lines on a single plot. From what I understand, the following code should…

libclang: add compiler system include path (Python in Windows)

Following this question and Andrews suggestions, I am trying to have liblang add the compiler system include paths (in Windows) in order for my Python codeimport clang.cindexdef parse_decl(node):refere…

Pako not able to deflate gzip files generated in python

Im generating gzip files from python using the following code: (using python 3)file = gzip.open(output.json.gzip, wb)dataToWrite = json.dumps(data).encode(utf-8)file.write(dataToWrite)file.close()Howev…

Best way to have a python script copy itself?

I am using python for scientific applications. I run simulations with various parameters, my script outputs the data to an appropriate directory for that parameter set. Later I use that data. However s…