Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django. Override save for model

Tags:

python

django

Before saving model I'm re-size a picture. But how can I check if new picture added or just description updated, so I can skip rescaling every time the model is saved?

class Model(model.Model):     image=models.ImageField(upload_to='folder')     thumb=models.ImageField(upload_to='folder')     description=models.CharField()       def save(self, *args, **kwargs):         if self.image:             small=rescale_image(self.image,width=100,height=100)             self.image_small=SimpleUploadedFile(name,small_pic)         super(Model, self).save(*args, **kwargs) 

I want to rescale only if new image loaded or image updated, but not when description updated.

like image 696
Pol Avatar asked Nov 24 '10 17:11

Pol


People also ask

How do I override a saved form?

To override the save method in the Python Django ModelForm, we add the save method into our model form class. to create the CallResultTypeForm that has its own save method. In it, we call the parent class' instance save method. And then we loop through the values in callResult to set them in the new m_new object.

How do I save models in Django?

Creating objects To create an object, instantiate it using keyword arguments to the model class, then call save() to save it to the database. This performs an INSERT SQL statement behind the scenes. Django doesn't hit the database until you explicitly call save() . The save() method has no return value.

What does save () return in Django?

1 and save() still returns None.


1 Answers

Some thoughts:

class Model(model.Model):     _image=models.ImageField(upload_to='folder')     thumb=models.ImageField(upload_to='folder')     description=models.CharField()      def set_image(self, val):         self._image = val         self._image_changed = True          # Or put whole logic in here         small = rescale_image(self.image,width=100,height=100)         self.image_small=SimpleUploadedFile(name,small_pic)      def get_image(self):         return self._image      image = property(get_image, set_image)      # this is not needed if small_image is created at set_image     def save(self, *args, **kwargs):         if getattr(self, '_image_changed', True):             small=rescale_image(self.image,width=100,height=100)             self.image_small=SimpleUploadedFile(name,small_pic)         super(Model, self).save(*args, **kwargs) 

Not sure if it would play nice with all pseudo-auto django tools (Example: ModelForm, contrib.admin etc).

like image 110
petraszd Avatar answered Sep 21 '22 05:09

petraszd