Return image url in Django Rest Framework

Updating the image field in the serializer to use_url=True worked for me:

class PictureSerialiser(serializers.ModelSerializer):
    image = serializers.ImageField(
            max_length=None, use_url=True
        )
    class Meta:
        model = Picture
        fields = ('field', 'image')

I wasn't able to get the currently accepted answer (adding a custom get_image_url method to the serializer) to work in Django 2.2. I was getting error messages that I needed to update my model to include the field image_url. Even after updating the model it wasn't working.


Provided answers are all correct, But I want to add a point to answers, and that is a way to return the path of the file including the address of the site. To do that, we get help from the request itself:

class PictureSerialiser(serializers.ModelSerializer):

    image_url = serializers.SerializerMethodField('get_image_url')

    class Meta:
        model = Picture
        fields = ('field',
                  'image',
                  'image_url')

    def get_image_url(self, obj):
        request = self.context.get("request")
        return request.build_absolute_uri(obj.image.url)

def get(self, request, aid):
'''
Get Image
'''
try:
    picture = Picture.objects.filter(some_field=aid)
except Picture.DoesNotExist:
    raise Http404

serialiser = PictureSerialiser(picture, context={'request': request}) # Code Added here
return Response(serialiser.data)

in your get views just add context={'request': request}. And It may work fine. My code is working and I am getting full url of Image. DRF Docs


You could do this with a custom serializer method like so:

class PictureSerialiser(serializers.ModelSerializer):

    image_url = serializers.SerializerMethodField('get_image_url')

    class Meta:
        model = Picture
        fields = ('field', 'image', 'image_url')

    def get_image_url(self, obj):
        return obj.image.url