Home > Blockchain >  How to send a link to an image in a response
How to send a link to an image in a response

Time:09-16

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

CodePudding user response:

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

CodePudding user response:

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'
  • Related