问题描述
我是 Django 的初学者,目前我可以构建这样的模型.
I am beginner to Django and currently, I can construct model like this.
模型.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')
序列化器.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)
对于照片,它不显示完整的 URL.如何显示完整网址?
For photo, it doesn't show full URL. How can I show full URL?
推荐答案
Django 没有提供存储在 models.ImageField
中的图像的绝对 URL(至少如果你不包括MEDIA_URL
中的域名a>; 不建议包含域,除非您将媒体文件托管在不同的服务器(例如 aws)上).
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)).
但是,您可以修改序列化程序以使用自定义 serializers.SerializerMethodField
.在这种情况下,您的序列化程序需要进行如下更改:
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)
还要确保你已经设置了 Django 的 MEDIA_ROOT
和 MEDIA_URL
参数,您可以通过浏览器访问照片http://localhost:8000/path/to/your/image.jpg代码>.
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
.
正如piling所指出的,您需要在views.py中初始化序列化程序时添加请求:
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
这篇关于Django 序列化程序 Imagefield 以获取完整 URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!