Return image url in Django Rest Framework

后端 未结 4 2177
孤街浪徒
孤街浪徒 2020-12-31 11:05

I am using Django Rest Framework and have the following model:

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


        
相关标签:
4条回答
  • 2020-12-31 11:12
    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)
    

    in your get views just add context={'request': request}. And It may work fine. My code is working and I am getting full url of Image. DRF Docs

    0 讨论(0)
  • 2020-12-31 11:17

    You could do this with a custom serializer method like so:

    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
    
    0 讨论(0)
  • 2020-12-31 11:26

    Updating the image field in the serializer to use_url=True worked for me:

    class PictureSerialiser(serializers.ModelSerializer):
        image = serializers.ImageField(
                max_length=None, use_url=True
            )
        class Meta:
            model = Picture
            fields = ('field', 'image')
    

    I wasn't able to get the currently accepted answer (adding a custom get_image_url method to the serializer) to work in Django 2.2. I was getting error messages that I needed to update my model to include the field image_url. Even after updating the model it wasn't working.

    0 讨论(0)
  • 2020-12-31 11:29

    Provided answers are all correct, But I want to add a point to answers, and that is a way to return the path of the file including the address of the site. To do that, we get help from the request itself:

    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)
    
    0 讨论(0)
提交回复
热议问题