pythonjsondjangoserializationdjango-imagekit

django-imagekit - thumbnail field not getting serialized


I have following problem:

I'm writing an AJAX view in django that serves JSON data about image list from a model that uses ImageSpecField from django-imagekit extension:

class Image(models.Model):
   title = models.CharField(max_length=120)
   img = models.ImageField(upload_to="images")
   thumb = ImageSpecField(source="img",
       id="core:image:image_thumbnail"
     )
   objects = models.Manager()
   json_data = JSONConvertibleManager()

The model uses custom manager for conversion into JSON (JSONConvertibleManager) using built-in Django serializer (instance of django.core.serializers).

My problem is that all the fields are properly serialized except for the ImageSpecField which is getting completely ommited. Is it possible to return instance.thumb.url value during serialization?


Solution

  • Just for info I was using Django Rest Framework and so used the serializer class from that library.

    My model:

    class Photo(models.Model):
        """ Photograph """
        title = models.CharField(max_length=100)
        slug = models.SlugField(max_length=255)
        original_image = models.ImageField(upload_to='boxes')
        formatted_image = ImageSpecField(source='original_image', format='JPEG',
            options={'quality': 90})
        thumbnail = ImageSpecField([Adjust(contrast=1.2, sharpness=1.1),
            ResizeToFill(200, 115)], source='original_image',
            format='JPEG', options={'quality': 90})
        num_views = models.PositiveIntegerField(editable=False, default=0)
    

    My serializer:

    class PhotoSerializer(serializers.ModelSerializer):
        original_image = serializers.Field('original_image.url')
        thumbnail = serializers.Field('thumbnail.url')
    
        class Meta:
            model = Photo
            fields = ('id', 'title', 'original_image', 'thumbnail',)