How to send a link to an image in a response

Viewed 38

I want to send a link to a photo in the response, which is on the hosting, I'm running a django application on the hosting via python manage.py runserver 0.0.0.0:8000 . How do I make it so that in the response to the request there is a link to the image that is on the hosting.

Example: I get this response when accessing the API

{
    "title": "add",
    "description": "some text",
    "image": "http://127.0.0.1:8000/media/photo_2022-09-12_20-57-08.jpg",
    "created_at": "2022-09-12T22:24:42.449098+03:00"
}

I want to get this answer:

{
    "title": "add",
    "description": "some text",
    "image": "domain.api/media/photo_2022-09-12_20-57-08.jpg",
    "created_at": "2022-09-12T22:24:42.449098+03:00"
}


models.py

class Event(models.Model):
    title = models.TextField()
    description = models.TextField()
    image = models.ImageField(blank=True)
    is_main = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.title

views.py

class EventDetailOrList(viewsets.ReadOnlyModelViewSet):
    queryset = Event.objects.all()
    serializer_class = EventSerializer
    filter_backends = (filters.DjangoFilterBackend,)
    filterset_class = EventFilter
3 Answers

I would use the socket module to grab the hostname of the IP:

import socket
     
address = 127.0.0.1:8000
host = socket.gethostbyaddr(address)
 
return host

If you have access to the request object you can do something like

request.META['REMOTE_ADDR']         # '127.0.0.1'
root = request.META['HTTP_HOST']    # '127.0.0.1:8000'

# combined with: 
from django.templatetags.static import static
path = static('media/nealium_avatar.png')


full = '{0}/{1}'.format(root, path)
# full = '127.0.0.1:8000/static/media/nealium_avatar.png'

Let's do it step by step:

1. settings.py

INSTALLED_APPS = [
...
...
...
'django.contrib.sites',
...
...
]


SITE_ID = 1

after that, you need to run migrate

python manage.py migrate

2. models.py

class Event(models.Model):
    title = models.TextField()
    description = models.TextField()
    image = models.ImageField(blank=True)
    is_main = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)

    def get_image(self):
        if self.image:
            return Site.objects.get_current().domain + self.image.url
        else:
            return ""

3. serializers.py

class EventSerializer(serializers.ModelSerializer):
    class Meta:
        model = Event
        fields = [
            'title',
            'description',
            'get_image',
            'created_at',
        ]

after these steps, you can edit your site domain on the Django Admin panel.

I hope this helps!

Related