BEST METHOD SO FAR
You must be getting the path to the image as something like this
image_field: "media/path/to/your/image.jpg"
But what you really want in response is image_field: "http://localhost/media/path/to/your/image.jpg"
STEP: 1
In your model provide attribute "upload_to" in the field:
#models.py
YourModel(models.Model):
image_field = models.ImageField(upload_to='images/', null = True)
STEP: 2
Add this in settings.py, It will ensure a media directory is created for all your images
#settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
STEP: 3
Add a configuration to your urls.py. It will ensure your images are accessible over a url.
#urls.py
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
...#some paths
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
STEP: 4
In you serializer add these lines
#serializers.py
class YourModelSerializer(serializers.ModelSerializer):
class Meta:
model = models.YourModel
fields = '__all__'
#This is the magic function which does the work
def get_photo_url(self, obj):
request = self.context.get('request')
photo_url = obj.fingerprint.url
return request.build_absolute_uri(photo_url)
You might wonder about "context", "request", "obj" , This will make sense in step 5
STEP: 5
Now atlast in your Views.py, we have to provide the request, context to Serializer.
#views.py
class YourModelView(APIVIew):
def get(self, request, format=None):
queryset = models.YourModel.objects.all()
serializer = serializers.YourModelSerializer(queryset, context={"request":
request}, many=True)
return Response(serializer.data)
After following these steps you will be getting the required image_url in your Response
Have a nice day!!!