Categories
Python Answers

How to get the full URL of the image value of a Python Django REST framework Imagefield?

Spread the love

Sometimes, we want to get the full URL of the image value of a Python Django REST framework Imagefield.

In this article, we’ll look at how to get the full URL of the image value of a Python Django REST framework Imagefield.

How to get the full URL of the image value of a Python Django REST framework Imagefield?

To get the full URL of the image value of a Python Django REST framework Imagefield, we can get it from the image value’s url property.

For instance, we write

class CarSerializer(serializers.ModelSerializer):
    photo_url = serializers.SerializerMethodField()

    class Meta:
        model = Car
        fields = ('id','name','price', 'photo_url') 

    def get_photo_url(self, car):
        request = self.context.get('request')
        photo_url = car.photo.url
        return request.build_absolute_uri(photo_url)

to create the CarSerializer that get the URL of the car.photo image from car.photo.url.

And then we call request.build_absolute_uri with the URL to return the absolute URL.

Conclusion

To get the full URL of the image value of a Python Django REST framework Imagefield, we can get it from the image value’s url property.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *