Skip to content
Advertisement

Django REST Framework and FileField absolute url

I’ve defined a simple Django app that includes the following model:

JavaScript

(Technically yes, that could have been an ImageField.)

In a template, it’s easy enough to include the MEDIA_URL value (duly coded in settings.py) as a prefix to the thumbnail URL. The following works fine:

JavaScript

Using DRF, I’ve defined a HyperlinkedModelSerializer descendant called ProjectSerializer:

JavaScript

And I’ve defined a very straightforward ModelViewSet descendant:

JavaScript

A sample of the resulting JSON looks like this:

JavaScript

I have not yet been able to figure out how to provide a thumbnail field that includes the full url to the image in my project’s JSON representation.

I would think that I would need to create a custom field in the ProjectSerializer, but have not been successful.

Advertisement

Answer

Try SerializerMethodField

Example (untested):

JavaScript

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:

JavaScript
Advertisement