matthewwithanm / django-imagekit

Automated image processing for Django. Currently v4.0
http://django-imagekit.rtfd.org/
BSD 3-Clause "New" or "Revised" License
2.26k stars 276 forks source link

How to create Serializer for ImageSpecField? #432

Open EvanZ opened 6 years ago

EvanZ commented 6 years ago

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?

vstoykov commented 6 years ago

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.

lengzuo commented 6 years ago

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