Django REST Framework and FileField absolute url Django REST Framework and FileField absolute url python python

Django REST Framework and FileField absolute url


Try SerializerMethodField

Example (untested):

class MySerializer(serializers.ModelSerializer):    thumbnail_url = serializers.SerializerMethodField('get_thumbnail_url')    def get_thumbnail_url(self, obj):        return self.context['request'].build_absolute_uri(obj.thumbnail_url)

The request must available to the serializer, so it can build the full absolute URL for you. One way is to explicitly pass it in when the serializer is created, similar to this:

serializer = MySerializer(account, context={'request': request})


Thanks, shavenwarthog. Your example and documentation reference helped enormously. My implementation is slightly different, but very close to what you posted:

from SomeProject import settingsclass ProjectSerializer(serializers.HyperlinkedModelSerializer):    thumbnail_url = serializers.SerializerMethodField('get_thumbnail_url')    def get_thumbnail_url(self, obj):        return '%s%s' % (settings.MEDIA_URL, obj.thumbnail)    class Meta:        model = Project        fields = ('id', 'url', 'name', 'thumbnail_url') 


To get the url of a file which uses FileField you can just call the url attribute of the FieldFile (this is the file instance not the field), it use the Storage class to determine the url for this file. It's very straightforward if you are using a external storage like Amazon S3 or if your storage changes.

The get_thumbnail_url would be like this.

def get_thumbnail_url(self, obj):    return obj.thumbnail.url

You can also use it in the template this way:

{{ current_project.thumbnail.url }}