0

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')]}
6
  • share the error detail Commented Mar 9, 2020 at 2:23
  • @Mirza715 just edited my post. Commented Mar 9, 2020 at 2:27
  • ` response = requests.get(img_url) to response = requests.file.get(img_url) Commented Mar 9, 2020 at 2:29
  • img_url = request.FILES.get("picture") do this and you will get the File. Commented Mar 9, 2020 at 2:43
  • request has neither file nor files as attribute... Commented Mar 9, 2020 at 2:49

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.