在Django Rest Framework中返回图片网址

时间:2014-10-15 10:08:01

标签: python django django-rest-framework

我正在使用Django Rest Framework并拥有以下模型:

class Picture(models.Model):
    some_field = models.ForeignKey(some_model)
    image = models.ImageField()

我想写一个返回图像网址的GET端点。这是我到目前为止所做的事情

def get(self, request, aid):
    '''
    Get Image
    '''
    try:
        picture = Picture.objects.filter(some_field=aid)
    except Picture.DoesNotExist:
        raise Http404

    serialiser = PictureSerialiser(picture)
    return Response(serialiser.data)

和我的Serialiser如下:

class PictureSerialiser(serializers.ModelSerializer):

    class Meta:
        model = Picture
        fields = ('field', 'image')

如何确保回复为{field:'Value here', image:'url to image'}

6 个答案:

答案 0 :(得分:14)

您可以使用自定义序列化方法执行此操作:

class PictureSerialiser(serializers.ModelSerializer):

    image_url = serializers.SerializerMethodField('get_image_url')

    class Meta:
        model = Picture
        fields = ('field', 'image', 'image_url')

    def get_image_url(self, obj):
        return obj.image.url

答案 1 :(得分:5)

提供的答案都是正确的,但是我想在答案上添加一个点,这是一种返回文件路径(包括站点地址)的方法。为此,我们可以从请求本身获取帮助:

class PictureSerialiser(serializers.ModelSerializer):

    image_url = serializers.SerializerMethodField('get_image_url')

    class Meta:
        model = Picture
        fields = ('field',
                  'image',
                  'image_url')

    def get_image_url(self, obj):
        request = self.context.get("request")
        return request.build_absolute_uri(obj.image.url)

答案 2 :(得分:1)

将序列化程序中的image字段更新为function searchString(){ var sheet = SpreadsheetApp.getActiveSheet() var search_string = "dog" var textFinder = sheet.createTextFinder(search_string) var search_row = textFinder.findNext().getRow() var ui = SpreadsheetApp.getUi(); ui.alert("search row: " + search_row) } 对我有用:

use_url=True

我无法获得当前接受的答案(向序列化器添加自定义get_image_url方法)以在Django 2.2中工作。我收到错误消息,我需要更新我的模型以包含字段image_url。即使在更新模型后,它也无法正常工作。

答案 3 :(得分:0)

def get(self, request, aid):
'''
Get Image
'''
try:
    picture = Picture.objects.filter(some_field=aid)
except Picture.DoesNotExist:
    raise Http404

serialiser = PictureSerialiser(picture, context={'request': request}) # Code Added here
return Response(serialiser.data)

在您的获取视图中,只需添加context={'request': request}。而且它可能工作正常。我的代码正在运行,并且我正在获取Image的完整URL。 DRF Docs

答案 4 :(得分:0)

目前最好的方法

您必须像这样获取图像的路径 image_field: "media/path/to/your/image.jpg"

但你真正想要的回应是 image_field: "http://localhost/media/path/to/your/image.jpg"

步骤:1 在您的模型中,在字段中提供属性“upload_to”:

#models.py
YourModel(models.Model):
    image_field = models.ImageField(upload_to='images/', null = True)

步骤:2 在 settings.py 中添加它,它将确保为您的所有图像创建一个媒体目录

 #settings.py
    MEDIA_ROOT  = os.path.join(BASE_DIR, 'media')
    MEDIA_URL = '/media/'

步骤:3 将配置添加到您的 urls.py。它将确保您的图片可通过网址访问。

 #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)

步骤:4 在您的序列化程序中添加这些行 #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)

您可能想知道 "context", "request", "obj" ,这在第 5 步中很有意义

步骤:5 现在在您的 Views.py 中,我们必须向 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) 

按照这些步骤操作后,您将在响应中获得所需的 image_url

祝你有美好的一天!!!

答案 5 :(得分:0)

<块引用>

serializers.py

make -j $(nproc) TARGET=generic USE_GZIP=1 USE_OPENSSL=1 USE_ZLIB=yes SSL_INC=/usr/local/include SSL_LIB=/usr/local/lib64
<块引用>

views.py

class ListImageSerializer(serializers.ModelSerializer):

    class Meta:
        model = UploadImg
        fields = [
            'id',
            'image'
        ]

只需在您的 class ListImageAPIView(generics.ListAPIView): serializer_class = ListImageSerializer queryset = UploadImg.objects.all() permission_classes = [IsAuthenticated] def get(self, request, format=None): imgobj = UploadImg.objects.all() serializer = ListImageSerializer(imgobj, many=True, context= {'request': request}) return Response({ 'status' : True, 'message' : 'Image List', 'images' : serializer.data}) 文件的序列化器对象中添加 context= {'request': request}) 行,您就可以开始了

<块引用>

回复

views.py