简体   繁体   中英

Save Image from url Django Rest Framework

I'm trying to save an image from a url in the post request.

Here is what I have so far, the error is while passing the file to the serializer.

#models.py
class Picture(models.Model):
    picture = models.ImageField(
        upload_to=upload_location_picture, max_length=255
    )
    owner = models.ForeignKey(
        User, on_delete=models.CASCADE, related_name='owned_pictures')

#views.py
class PlanPostPictureByUrl(APIView):
    '''
    Class to post dislike to plan
    '''
    permission_classes = (permissions.IsAuthenticated,)

    def post(self, request, format=None):
        img_url = request.data["picture"]
        name = urlparse(img_url).path.split('/')[-1]
        response = requests.get(img_url)
        if response.status_code == 200:
            serializer = PlanPicturesSerializer(
                data={"picture":ContentFile(response.content)})
        if serializer.is_valid():
            serializer.save(owner=self.request.user)
            return Response(status=status.HTTP_201_CREATED)
        return Response(status=status.HTTP_400_BAD_REQUEST)


#serializers.py
class PlanPicturesSerializer(serializers.ModelSerializer):

    class Meta:
        model = Picture
        fields = ['picture']

This is the error I am getting from the serializer:

{'picture': [ErrorDetail(string='No filename could be determined.', code='no_name')]}

I have something like this in my serializers create and update methods.

from django.core.files.uploadedfile import UploadedFile

url = validated_data['newIconFromURL']
# Remove url from the submitted data
validated_data['newIconFromURL'] = ''
# Download data from url (requires `requests` module.  Can also be done with urllib)
response = requests.get(validated_data['newIconFromURL'])
# Set icon field (ImageField) to binary file
validated_data['icon'] = UploadedFile(BytesIO(response.content), name='icon')

Note that the file name does not need to be unique, as Django will append random characters to the actual filename to make it unique.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM