0

How i get image location with full url

models.py

class UploadImage(models.Model):

img_id = models.AutoField(primary_key=True)
image = models.ImageField(upload_to='images/')

def __str__(self):
    return str(self.image) 

serializers.py

class UploadedImageSerializer(serializers.ModelSerializer):

    class Meta:
    model = UploadImage
    fields = [
        'img_id',
        'user_id',
        'image',

2 Answers2

0

Get image location with url in response in django rest framework is very easy

just follow simple step and you will get the answer

first add some details and path in settings.py and urls.py so that django identify you will upload an image and where to save that image

project/settings.py

MEDIA_URL = '/media/' #django will autometically made the media folder at project level
MEDIA_ROOT = os.path.join(BASE_DIR, "media")

project/urls.py

from django.conf import settings
from django.conf.urls.static import static

if settings.DEBUG:
  urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

app/models.py

class UploadImage(models.Model):

img_id = models.AutoField(primary_key=True)
image = models.ImageField(upload_to='images/') #it will save image(s) in media/images folder

def __str__(self):
    return str(self.image) 

app/serializers.py

class UploadedImageSerializer(serializers.ModelSerializer):

    class Meta:
    model = UploadImage
    fields = [
        'img_id',
        'image',

app/views.py

class UploadedImageAPIView(generics.CreateAPIView):
    serializer_class = UploadedImageSerializer
    queryset = UploadImage.objects.all()

    def post(self, request):
        image = request.data.get('image', False)
        serializer = UploadedImageSerializer(data=request.data, context={'request': request}) 

        #context={'request': request will return full url
        #ex.http://192.168.1.24:8000/media/images/97800.0_8iOq60p.png

        if serializer.is_valid():
            serializer.save()
            return Response({
                'status': True, 
                'message': 'Image Upload Successfully',
                'data': serializer.data, 
            }, status = status.HTTP_201_CREATED)

        else:
            return Response({
            'status': False,
            'message': 'Error! Make sure image field is not empty',
            }, status = status.HTTP_400_BAD_REQUEST)

app/urls.py

urlpatterns = [
    url(r'^upload_img', UploadedImageAPIView.as_view())
]

Response

{
"status": true,
"message": "Image Upload Successfully",
"data": {
    "img_id": 1,
    "image": "http://192.168.1.24:8000/media/images/emoji_jrGNDyk.png"
}
}

I hope you get answer you are looking for:)

0

This has already been answered here: https://stackoverflow.com/a/35522896

In short: you can use a SerializerMethodField to return the relative URL for the ImageField and if you need the full URI you can use the Django method build_absolute_uri on that (https://docs.djangoproject.com/en/3.2/ref/request-response/#django.http.HttpRequest.build_absolute_uri)

Tom
  • 688
  • 13
  • 29