djangodjango-imagekit

How to specify image specs in Django imagekit outside the field definition?


I have the following model definition:

class Photo(models.Model) :
    def get_gallery_path(self, filename):
        ext = filename.split('.')[-1]
        filename = "%s.%s" % (uuid.uuid4(), ext)
        return 'static/uploads/images/gallery/' + filename

    uploader = models.ForeignKey(User, on_delete=models.CASCADE)
    date = models.DateField(default=date.today)
    image = ProcessedImageField(default='', verbose_name='Image', upload_to=get_gallery_path, processors=[ResizeToFill(100, 50)], format='JPEG', options={'quality': 60})
    caption = models.CharField(max_length=200, null=True, blank=True)

    def __str__(self):
        return str(self.id) + str(self.uploader.username) + str(self.date)

    class Meta:
        verbose_name_plural = "Photos"
        verbose_name = "Photo"

I have used django-imagekit to modify the uploaded images. But as you can see, I have to state all the properties and options inline in the image field. This makes the code hard to read when I specify many properties.

Is there a way to define the properties and options separately in the models.py file such that I can use it for all my image fields.


Solution

  • You can simply take advantage of dictionary unpacking.

    For example, define your dictionary processed_image_field_specs:

    def get_gallery_path(filename):
      ext = filename.split('.')[-1]
      filename = "%s.%s" % (uuid.uuid4(), ext)
      return 'static/uploads/images/gallery/' + filename
    
    processed_image_field_specs = {
      'default': '', 
      'verbose_name': 'Image', 
      'upload_to': get_gallery_path, 
      'processors': [ResizeToFill(100, 50)], 
      'format': 'JPEG', 
      'options': {'quality': 60}
    }
    

    Now unpack the dictionary to provide named arguments to ProcessedImageField:

    class Photo(models.Model) :
        ...
        image = ProcessedImageField(**processed_image_field_specs)
        ...