0

The docs on their GitHub page suggests that what I'm trying to do should work:

thumb_url = profile.photo['avatar'].url

In my project, it gives an error:

THUMBNAIL_ALIASES = {
    '': {
        'thumb': {'size': (64, 64), 'upscale': False},
    },
}

class Image(models.Model):
    place = models.ForeignKey(Place, models.CASCADE, 'images')
    image = ThumbnailerImageField(upload_to='')

class ImageSerializer(serializers.Serializer):
    image = serializers.ImageField()
    thumb = serializers.ImageField(source='image.image["thumb"].url')

AttributeError: Got AttributeError when attempting to get a value for field `thumb` on serializer `ImageSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `Image` instance.
Original exception text was: 'ThumbnailerImageFieldFile' object has no attribute 'image["thumb"]'.

The url of image is serialized properly if thumb is removed. How can I get DRF to serialize the url of the thumbnail?

davidtgq
  • 3,780
  • 10
  • 43
  • 80
  • Maybe you should use "image["thumb"]" instead of "image.image["thumb"]". – Yahya Yahyaoui Feb 02 '16 at 20:07
  • That gets a similar error: Got AttributeError when attempting to get a value for field `thumb` on serializer `ImageSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `Image` instance. Original exception text was: 'Image' object has no attribute 'image["thumb"]'. ` – davidtgq Feb 02 '16 at 20:10
  • I meant ""thumb = serializers.ImageField(source='image["thumb"].url'))""" – Yahya Yahyaoui Feb 02 '16 at 20:51
  • Yes that's exactly what I tried. I think it's the `["thumb"] that's not working right now. – davidtgq Feb 02 '16 at 20:53

1 Answers1

2

settings.py

THUMBNAIL_ALIASES = {
    '': {
        'avatar': {'size': (40, 40)},
        'image': {'size': (128, 128)},
    },
}

api/serializers.py

from easy_thumbnails.templatetags.thumbnail import thumbnail_url


class ThumbnailSerializer(serializers.ImageField):
    def __init__(self, alias, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.read_only = True
        self.alias = alias

    def to_representation(self, value):
        if not value:
            return None

        url = thumbnail_url(value, self.alias)
        request = self.context.get('request', None)
        if request is not None:
            return request.build_absolute_uri(url)
        return url

using

from api.serializers import ThumbnailSerializer


class ProfileSerializer(serializers.ModelSerializer):
    image = ThumbnailSerializer(alias='image')
    avatar = ThumbnailSerializer(alias='avatar', source='image')
IML
  • 181
  • 2
  • 7