I have found an issue in a project with Django REST Framework. Where in 'POST', I'll input only 1 image file but in 'GET', I will get the file path of that image file as well as I'll get another file path of resized version of that image.
In models, you'll see we have two image fields. original and thumbnail. we'll input in the only the original field. But the thumbnail will be filled automatically by a resized version of the image from the original field.
Models:
class BookCover(models.Model):
id = models.UUIDField(primary_key=True, max_length=36, default=uuid.uuid4)
original = models.ImageField()
thumbnail = ResizedImageField()
Serializers:
class BookCoverSerializer(serializers.ModelSerializer):
class Meta:
model = BookCover
fields = "__all__"
Views(for Creating):
def create(self, request,*args, **kwargs):
serializer = self.serializer_class(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(
Msg.encode(201, "Saved Successfully", None, serializer.data)
, status=status.HTTP_201_CREATED
)
return Response(
Msg.encode(400, None, serializer.errors, None)
, status=status.HTTP_400_BAD_REQUEST
)
Here, we'll give input to the original image, not the thumbnail. but in the table, we'll get the resized version of that original image in the thumbnail field.
How can we do this? Any help would be highly appreciated.
First, you should make sure the thumbnail field is read_only in your serializer, because you explicitly want it to be set from the original
field.
class BookCoverSerializer(serializers.ModelSerializer):
class Meta:
...
read_only_fields = ['thumbnail']
Then, you could implement the resizing within the serializer .save()
method. As an example (implement your own resize_image
method):
class BookCoverSerializer(serializers.ModelSerializer):
...
def save(self, **kwargs):
instance = super().save(**kwargs)
instance.thumbnail = resize_image(instance.original)
instance.save()
return instance
An easier approach would be to use something like the Django VersatileImageField