Reputation: 379
I have some issue with drf, can someone point out what am i doing wrong ?
This is my views function, I have also implemented easy_thumbnails so that i can crop the image if such a request is made.
from __future__ import unicode_literals
from django.shortcuts import render
from rest_framework import viewsets
from rest_framework.response import Response
from .models import Image
from .serializers import ImageSerializer
from easy_thumbnails.files import get_thumbnailer
class ImageViewSet(viewsets.ModelViewSet):
queryset = Image.objects.all()
serializer_class = ImageSerializer
def retrieve(self, request, pk=None):
height = request.GET.get('height', None)
width = request.GET.get('width', None)
print("height = {}".format(height))
print("width = {}".format(width))
print("id = {}".format(pk))
img = Image.objects.get(pk = pk)
if height and width:
options = {'size': (height, width), 'crop': True}
thumb_url = get_thumbnailer(img.image).get_thumbnail(options).url
else:
thumb_url = get_thumbnailer(img.image).url
return Response(thumb_url)
right now if goto http://127.0.0.1:8000/api/images/
it returns me a list of images
and http://127.0.0.1:8000/api/images/1/?height=320&width=420
returns a response like
HTTP 200 OK
Allow: GET, PUT, PATCH, DELETE, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept
"/media/10438039923_2ef6f68348_c.jpg.320x420_q85_crop.jpg"
I want a response like this with field names.
{
"title": "Item 1",
"description": "Description 1",
"image": "http://127.0.0.1:8000/media/10438039923_2ef6f68348_c.jpg"
}
How can i fix this issue ? I am new to drf and django
this is my serializer class
from rest_framework import serializers
from .models import Image
class ImageSerializer(serializers.ModelSerializer):
class Meta:
model = Image
fields = [
'title',
'description',
'image',
]
Upvotes: 0
Views: 533
Reputation: 3378
use this:
def retrieve(self, request, pk=None):
height = request.query_params.get('height', None)
width = request.query_params.get('width', None)
img = self.get_object()
if height and width:
options = {'size': (height, width), 'crop': True}
thumb_url = get_thumbnailer(img.image).get_thumbnail(options).url
else:
thumb_url = get_thumbnailer(img.image).url
serializer = self.get_serializer(img)
# insert thumb_url into data if you need it
response_dict = {}
response_dict.update(serializer.data)
response_dict['image'] = thumb_url
return Response(response_dict)
Upvotes: 2
Reputation: 9235
You could do this,
return Response({"title": img.title, "description": img.description,
"image": img.image, "thumbnail": thumb_url})
Upvotes: 0