Django serializer Imagefield to get full URL
Django is not providing an absolute URL to the image stored in a models.ImageField
(at least if you don't include the domain name in the MEDIA_URL
; including the domain is not recommended, except of you are hosting your media files on a different server (e.g. aws)).
However, you can modify your serializer to return the absolute URL of your photo by using a custom serializers.SerializerMethodField
. In this case, your serializer needs to be changed as follows:
class CarSerializer(serializers.ModelSerializer):
photo_url = serializers.SerializerMethodField()
class Meta:
model = Car
fields = ('id','name','price', 'photo_url')
def get_photo_url(self, car):
request = self.context.get('request')
photo_url = car.photo.url
return request.build_absolute_uri(photo_url)
Also make sure that you have set Django's MEDIA_ROOT
and MEDIA_URL
parameters and that you can access a photo via your browser http://localhost:8000/path/to/your/image.jpg
.
As piling pointed out, you need to add the request while initialising the serializer in your views.py:
def my_view(request):
…
car_serializer = CarSerializer(car, context={"request": request})
car_serializer.data
How can I get the full url of the image in DRF?
The FileField
and ImageField
automatically try to use the request
from the context
if it is passed to the serializer to build the absolute url. You should pass the context from your DiarySerializer
to the DiaryImageSerializer
:
class DiarySerializer(serializers.ModelSerializer):
images = serializers.SerializerMethodField()
def get_images(self, obj):
image = obj.diaryimage_set.all()
return DiaryImageSerializer(instance=image, many=True, context=self.context).data
# Rest of code
Get Image Field Absolute Path in Django Rest Framework - Non Request Flows
Got it working,
Added MEDIA_URL to my settings file as mentioned here.
It seems DRF uses MEDIA_URL as a default prefix for urls(FileField & ImageField), even for non request/response flows.
Since I had a different settings file for staging, development and production it was easier for me to set different URLs for each environment.
Even though I'm not using 'django-versatileimagefield' library, the suggestion there still worked.
How to get full url of static default image in django model
view.py:
data = WidgetSerializer(wight, context={'request': request}).data
serializer.py
class WidgetSerializer(serializers.HyperlinkedModelSerializer):
...
class Meta:
model = Widget
fields = ('image',
...
)
add context={'request': request}
to your serializer will get the full path of your image.more info here.
If you want to set it in serializer:
class WidgetSerializer(serializers.HyperlinkedModelSerializer):
image = serializers.SerializerMethodField()
class Meta:
model = Widget
fields = ('image',
...
)
def get_image(self, instance):
request = self.context.get('request')
return request.build_absolute_uri(instance.get_image())
model.py
class Widget(models.Model):
...
def get_image(self):
if self.image:
return self.image.url
else:
return settings.STATIC_URL + 'img/default/meal.png'
Send full image url in DRF
You should probably check that the url is not None :
def get_image_url(self, Vessel):
request = self.context.get('request')
image_url = Vessel.image.url if Vessel.image and hasattr(Vessel.image, 'url') else None
if image_url:
return request.build_absolute_uri(image_url)
return None
Django REST Framework and FileField absolute url
Try SerializerMethodField
Example (untested):
class MySerializer(serializers.ModelSerializer):
thumbnail_url = serializers.SerializerMethodField('get_thumbnail_url')
def get_thumbnail_url(self, obj):
return self.context['request'].build_absolute_uri(obj.thumbnail_url)
The request must available to the serializer, so it can build the full absolute URL for you. One way is to explicitly pass it in when the serializer is created, similar to this:
serializer = MySerializer(account, context={'request': request})
how i get image location with url using Generics API view in response in django rest framework
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:)
Related Topics
How to Read Datetime Back from SQLite as a Datetime Instead of String in Python
Interact with Other Programs Using Python
Finding Duplicate Files and Removing Them
Fitting a Normal Distribution to 1D Data
Extracting Specific Columns in Numpy Array
How to Normalize JSON Correctly by Python Pandas
Python: How to Remove Empty Lists from a List
Print Combining Strings and Numbers
Filedialog, Tkinter and Opening Files
Django Template System, Calling a Function Inside a Model
How to Programmatically Set a Global (Module) Variable
Removing Control Characters from a String in Python
Flask-Sqlalchemy Update a Row's Information
How to Make the Width of the Title Box Span the Entire Plot
Python List Comprehension - Want to Avoid Repeated Evaluation