Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return image url in Django Rest Framework

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

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

I would like to write a GET endpoint that returns the url of the image. This is what I've done so far

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)

and my Serialiser as follows:

class PictureSerialiser(serializers.ModelSerializer):

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

How do I make sure that the response is {field:'Value here', image:'url to image'}?

like image 356
Newtt Avatar asked Oct 15 '14 10:10

Newtt


People also ask

What is ViewSet in Django?

A ViewSet class is simply a type of class-based View, that does not provide any method handlers such as . get() or . post() , and instead provides actions such as . list() and . create() .

What is the difference between ModelSerializer and HyperlinkedModelSerializer?

The HyperlinkedModelSerializer class is similar to the ModelSerializer class except that it uses hyperlinks to represent relationships, rather than primary keys. By default the serializer will include a url field instead of a primary key field.

How can get image URL in Django REST Framework?

To get the full URL of the image value of a Python Django REST framework Imagefield, we can get it from the image value's url property. to create the CarSerializer that get the URL of the car.

How do you implement a search in DRF?

DRF is only looking for the search query parameter in question_text . We need to add author to search_fields too if we want search query parameter to be looked into author . Modify search_fields . Make api request again and you should see charles authored question in response.


4 Answers

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
like image 95
xxx Avatar answered Oct 19 '22 15:10

xxx


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.

like image 34
sadie parker Avatar answered Oct 19 '22 16:10

sadie parker


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)
like image 7
eng.mrgh Avatar answered Oct 19 '22 17:10

eng.mrgh


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

like image 2
Saim Avatar answered Oct 19 '22 16:10

Saim