django-imagekit icon indicating copy to clipboard operation
django-imagekit copied to clipboard

How to create Serializer for ImageSpecField?

Open EvanZ opened this issue 8 years ago • 2 comments

I'm uploading images to Google Cloud, and to display them to the client I want to create signed urls (this definitely works for my main ImageField). I'm using the same approach which is to derive a class from serializers.ImageField and override the to_representation class, but now I'm getting an error when I upload an image. I think it is expecting me to implement to_internal_value, but my assumption is that this wouldn't make sense since ImageSpecField should take care of that.

class ImageKitSerializer(serializers.ImageField):
    def to_representation(self, value):
        try:
            blob = Blob(name=value.name, bucket=bucket)
            signed_url = blob.generate_signed_url(expiration=datetime.timedelta(hours=2))
            return signed_url
        except ValueError as e:
            return value


class PhotoSerializer(serializers.ModelSerializer, TaggitSerializer):
    owner = serializers.CharField(source='owner.username', read_only=True)
    tags = TagListSerializerField()
    thumbnail = ImageKitSerializer()
    photo = Base64ImageField(use_url=True)

    class Meta:
        model = Photo
        fields = ('photo', 'height', 'width', 'owner', 'slug', 'uuid', 'title', 'id', 'created', 'updated',
                  'moderation_code', 'tags', 'hash', 'description', 'size', 'likes', 'thumbnail')

So I guess my question is how can I do something like this?

EvanZ avatar Sep 25 '17 00:09 EvanZ

Sorry for the late response. Did you manage to resolve your issue?

If not can you provide more information about the error that you are receiving? Without the error I can't help you because I have not used ImageKit with Google Cloud.

vstoykov avatar Oct 11 '17 11:10 vstoykov

Just declare thumbnail = serializers.ImageField(read_only=True) in your serializer for ImageSpecField.

lengzuo avatar Aug 23 '18 05:08 lengzuo