Search code examples
djangoimage-resizing

Can I use django fileds values in def functions?


I am trying to make a function to resize images before upload. I found something on interent and it is working but I want to improve it. Instead of having the output_size = (320, 560) [as default value always] I would like to have some django fields and change it every time I need from django admin. This is why I added image_height and image_width fields.

In my way of thinking doing this was the solution output_size = (image_height, image_width) but it doesnt work

output_size = (image_height, image_width)
NameError: name 'image_height' is not defined

How can I use image_height and image_width fields and use add the values to output_size

My models.py

from __future__ import unicode_literals
from django.db import models
from django.urls import reverse

from PIL import Image

def upload_location(instance, filename):
    return "%s/%s" %('image/service', filename)
# Create your models here.
class Services(models.Model):
    title  = models.CharField(max_length=120)
    content  = models.TextField(null=True, blank=True)
    image = models.ImageField(upload_to=upload_location, blank=True, null=True)
    image_height = models.PositiveIntegerField(default=320)
    image_width = models.PositiveIntegerField(default=560)
    
    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)
        img = Image.open(self.image.path)

        if img.height > 320 or img.weight > 560:
            output_size = (image_height, image_width)
            img.thumbnail(output_size)
            img.save(self.image.path)

    def __unicode__(self):
        return self.title

    def __str__(self):
        return self.title

Solution

  • Use self

    class Services(models.Model):
        # rest of your code
        def save(self, *args, **kwargs):
            super().save(*args, **kwargs)
            img = Image.open(self.image.path)
    
            if img.height > 320 or img.weight > 560:
    
                output_size = (self.image_height, self.image_width)
    
                img.thumbnail(output_size)
                img.save(self.image.path)