Jay P.
Jay P.

Reputation: 2590

How can I thumbnail images in serialization of Django REST Framework?

I recently jumped into Django REST Framework. Before using it, I thumbnailed images using django-imagekit. Like you see the models below, it worked well, so I used original size images from image and thumbnailed size images from image_thumbnail.

models.py

class Image(models.Model):
    ...
    image = ProcessedImageField(null=True, blank=True, upload_to=image_path,
                                processors=[Thumbnail(1000, 1400)], format='JPEG')
    image_thumbnail = ImageSpecField(
        source='image', format='JPEG', options={'quality': 40})
    ...

The problem is I can't use image_thumbnail in my serializers. I can use image, but image_thumbnail throws an error message A server error occurred. Please contact the administrator.

serializers.py

class ImageRandomSerializer(ModelSerializer):

    class Meta:
        model = Image
        fields = ('image', 'image_thumbnail', )

Can I not thumbnailed images from models.py in serializers.py? Should I thumbnail them with some Django REST Framework thumbnail tool?

UPDATE

After setting DEBUG=True, it throws the error 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte.

Upvotes: 0

Views: 1291

Answers (1)

Jay P.
Jay P.

Reputation: 2590

I just found the answer from here.

Added image_thumbnail = ImageField(read_only=True), and now it's working well.

from rest_framework.serializers import ImageField

class ImageRandomSerializer(ModelSerializer):

    store = StoreDomainKeySerializer()
    image_thumbnail = ImageField(read_only=True)

    class Meta:
        model = Image
        fields = ('store', 'image', 'image_thumbnail',)

Upvotes: 4

Related Questions