I am creating an API that saves images in a django model. Through the API is sent a URL and django is responsible for downloading the image and saving it in the model.
This is my model:
class Picture(Media):
image = models.ImageField(upload_to=picture_path, blank=True, null=True)
entity = models.CharField(max_length=20, choices=ENTITIES,
default=ENTITY_CLASIFICADO)
This is my serializer:
class PictureSerializer(serializers.ModelSerializer):
image = serializers.ImageField(max_length=None, use_url=True)
class Meta:
model = Picture
fields = ("pk", "image", "entity",)
From the URL I generate a PIL object. How do I specify the serializer that stores the object? My views.py
class PictureViewSet(generics.ListCreateAPIView):
def create(self, request, *args, **kwargs):
r = requests.get(request.data["url"])
img_temp = NamedTemporaryFile(delete = True)
img_temp.write(r.content)
Now, I'm saving the empty image field.
serializer = self.get_serializer(data=request.data)
I would like to add the PIL object to request.data and it looks like this:
<QueryDict: {'url': ['https://s3.amazonaws.com/cat/encabezado.jpg'], 'image': ['MY PIL IMAGE'], 'entity': ['clasificado'], 'csrfmiddlewaretoken': ['JRMLIXkxqg6sF5YP19NLTvgFOmVWH9ARSmM']}>
Thanks!
you can do that directly in serialiser
So basically it is real life working example, note that we need to set image as relative path when setting it in attrs
.
Also you need to check status of response, but this i'll leave up to you )
import os, uuid, requests
from django.conf import settings
from rest_framework.serializers import ModelSerializer
from .models import Audio
class AudioCreateSerializer(ModelSerializer):
class Meta:
model = Audio
fields = ['image']
def validate(self, attrs):
url = "http://youurlgoeshere.com/sddsjdsjdsjds.png"
data = requests.get(url)
response = requests.get(image_url)
random_name = uuid.uuid4().hex + ".png"
folder_name = "custom_images"
absolute_file_path = os.path.join(settings.MEDIA_ROOT, folder_name, random_name)
relative_path = os.path.join(folder_name, random_name)
with open(absolute_file_path, 'wb') as f:
f.write(response.content)
attrs['image'] = relative_path
return attrs
Also, i'll leave here how to define views
class AudioListView(ListCreateAPIView):
renderer_classes = [JSONRenderer]
queryset = Audio.objects.select_related("artist")
def get_serializer_class(self):
if self.request.method == "GET":
return AudioListSerializer
if self.request.method == "POST":
return AudioCreateSerializer
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.