1

I am writing a rest api application in the django rest framework in which I can post images.

I want to receive the url of the image: https://path/image_name.jpg

Here is my serializer class:

class Serializer(serializers.ModelSerializer):
url = serializers.SerializerMethodField('get_image_url')
...
def get_image_url(self, obj):
    return obj.image.url

In this case /media/filename.jpg is returned

If I add the https prefix, the link will be displayed, but if I click on it I get an error: browser can not connect to the server localhost

Sah9
  • 49
  • 4

2 Answers2

0

I'm not sure, but you can definitely use request.get_raw_uri() to get the hostname with its protocol. Trying something like image_url request.get_raw_uri() + url , This will generate proper url of the image.

0

You could use the serializers.ImageField which will do all the conversions.

class Serializer(serializers.ModelSerializer):
    url = serializers.ImageField(source='image')

Alternatively, you can just add 'image' to your Serializer.Meta.fields since that is a ModelSerializer and will generate everything for you (although the key would be image instead of url, but that shouldn't be an issue).

Alexandr Tatarinov
  • 3,946
  • 1
  • 15
  • 30