Search code examples
djangodjango-modelsdjango-adminsorl-thumbnail

Resizing and updating image in Django


I'm overriding my save method because I want to resize my image. My problem is obvious in this code, what happens after I save my data is that django starts an endless loop. Of course is because I'm checking if self.vertical is set or not (and is always set). Save method is always called.

I could solve this problem checking if my self.id is none, but the code will work only for new entries, if the user tries to update, nothing changes because the id is not null.

I also tried to pop an false argument to kwargs and after saving, set true, but also didnt work. Someone has an idea how can I solve this?

PS: get_thumbnail is a method of sorl thumbnail plugin.

    def save(self, *args, **kwargs):
        if self.vertical_poster: 
            super(Movie, self).save(*args, **kwargs)

            resized_vertical = get_thumbnail(self.vertical_poster, "155x240", quality=99)            

            #save the new resized file            
            self.vertical_poster.save(resized_vertical.name, ContentFile(resized_vertical.read()), True)

         super(Movie, self).save(*args, **kwargs)

Any idea or sample code will be appreciated! Thanks


Solution

  • My solution was not override my save method. I did something different:

    I decided to use "django-resized". This plugin is compatible with "sorl-thumbnail" and resizes image origin to specified size on the model field, as below:

    from django_resized import ResizedImageField
    
    class Movie(models.Model):
    
        ....
    
        vertical_poster = ResizedImageField(upload_to="movies", width=155, height=240)
    

    I hope that can help other people.

    Link: https://github.com/un1t/django-resized