I am beginner to Django and currently, I can construct model like this.
models.py
class Car(models.Model):
name = models.CharField(max_length=255)
price = models.DecimalField(max_digits=5, decimal_places=2)
photo = models.ImageField(upload_to='cars')
serializers.py
class CarSerializer(serializers.ModelSerializer):
class Meta:
model = Car
fields = ('id','name','price', 'photo')
views.py
class CarView(APIView):
permission_classes = ()
def get(self, request):
car = Car.objects.all()
serializer = CarSerializer(car)
return Response(serializer.data)
For photo, it doesn't show full URL. How can I show full URL?
It's better to use this code, due to the above code doesn't check the image is null able or not.
For future visitors, there is no need to add another field to the serializer if the view method already returns a serialized object. The only thing required is to add the context since it is needed to generate hyperlinks, as stated in the drf documentation
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 theMEDIA_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:Also make sure that you have set Django's
MEDIA_ROOT
andMEDIA_URL
parameters and that you can access a photo via your browserhttp://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:
Serializer class
View