Reputation: 4010
In my models.py
, I override save()
to manipulate the ImageField before saving it.
class Image(models.Model):
caption = models.Charfield(max_length=254)
image = models.ImageField(upload_to='')
def save(self, *args, **kwargs):
if self.image:
# image manipulations
super(Image, self).save(*args, **kwargs)
The manipulation should not run on the image if the object is saved without changing the ImageField, i.e. the user changes some other field like a CharField and updates the object. I didn't test this, but I presume that in the above code, self.image will always be True even if the user saves without uploading a new image to replace the old one.
So, I plan to check this based on whether or not an image file was uploaded by the user to begin with:
if form.is_valid():
instance = form.save(commit=False)
if form.cleaned_data.get('image'):
image_was_uploaded = True
instance.save(image_was_uploaded=image_was_uploaded)
Is this a valid method to accomplish this, or is there a better/more Pythonic approach (that hopefully works within models.py
so Admin and DRF benefit from the same functionality)?
Upvotes: 1
Views: 586
Reputation: 221
I would do it in the form class itself by overriding the clean method and checking it. when you call is_valid() from your view then it will inturn call the clean method where you can do this checking.
Upvotes: 0
Reputation: 434
You may want to look at a custom ImageField, which would handle your custom processing in its clean method. Take a look at this for instance: https://djangosnippets.org/snippets/2206/
Upvotes: 2