In Django Rest Framework Serializer, how to get the full path of image?

Issue

In my project, I want to get the full path of image using Serializer class.

When I use ViewSet class, it seems to get correct result. But when using APIView class, it doesn’t get what I need.

# the model
class UserAccount(models.Model):
    ...
    icon = models.ImageField(upload_to='icon/user')
# the serializer
class UserSerializer(serialziers.ModelSerializer):
    class Meta:
        model = UserAccount
        fields = (..., 'icon')

Use ViewSet

# viewset
class UserViewSet(viewsets.ModelViewSet):
    ...
    serializer_class = UserSerializer

# result
# {..., 'icon': 'http://127.0.0.1:8000/media/icon/user/filename'}

Use APIView

class UserView(APIView):
...
def get(self, request):
    ...
    userAccount = user.userAccount
    serializer = UserSerializer(userAccount)
    return Response(serializer.data)

# result
# {..., 'icon': '/media/icon/user/filename'}

What should I do to get full path of the image in APIView?

Solution

You need to add additional field with SerializerMethodField:

class UserSerializer(serializers.ModelSerializer):
    icon_url = serializers.SerializerMethodField()

    class Meta:
        model = UserAccount
        fields = (..., 'icon_url') 

    def get_icon_url(self, user_account):
        request = self.context.get('request')
        icon_url = user_account.icon.url
        return request.build_absolute_uri(icon_url)

And add request to context in view:

def get(self, request):
    ...
    userAccount = user.userAccount
    serializer = UserSerializer(userAccount, context={'request':request})
    return Response(serializer.data)

Answered By – Sergey Pugach

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published