Django序列化程序Imagefield获取完整的URL [英] Django serializer Imagefield to get full URL

查看:225
本文介绍了Django序列化程序Imagefield获取完整的URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Django的初学者,目前,我可以构建这样的模型。

I am beginner to Django and currently, I can construct model like this.

models.py

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

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)

对于照片,它不会显示完整的URL。如何显示完整的URL?

For photo, it doesn't show full URL. How can I show full URL?

推荐答案

Django没有为 models.ImageField (至少如果您未在 MEDIA_URL ;不建议包含域,除非您将媒体文件托管在其他服务器上(例如,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_ROOTand MEDIA_URL parameters and that you can access a photo via your browser http://localhost:8000/path/to/your/image.jpg.

正如桩指出的那样,您需要在初始化视图中的序列化程序时添加请求。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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆