If you have any ImageField or FileField in your model, you can easily display the full URL (including the hostname/domain) for the file/image. Django REST Framework’s model serializers would do it for you. However, to get the hostname/domain name, the serializer needs a “request context” so it can infer the necessary parts and build a full url.
So if you’re manually invoking a serializer, please pass a request context like this:
1 |
serialized_store = StoreSerializer(store, context={"request": request}) |
If you use ModelViewSet, DRF will automatically pass the request context while initializing the serializer. So in that case you don’t need to do anything. You need to pass the context only when you’re manually creating a serializer instance.
Thumbs Up đŸ™‚
I want to disable absolute url (http://127.0.0.1:80/media/profile/default.png) when using ModelViewSet with SimpleRouter. I want relative url(/media/profile/default.png).Is it possible ?
Thanks in advance Bro.
It should be possible. Just create a new method on your model.
Set directive in your settings.py for DRF. It disable absolute url.
REST_FRAMEWORK = {
…
‘UPLOADED_FILES_USE_URL’: False
…
}
Thanks man. great post.
Thanks! This help me đŸ˜€