django-imagekit
django-imagekit copied to clipboard
How to create Serializer for ImageSpecField?
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?
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.
Just declare thumbnail = serializers.ImageField(read_only=True) in your serializer for ImageSpecField.