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')]}
response = requests.get(img_url)toresponse = requests.file.get(img_url)img_url = request.FILES.get("picture")do this and you will get the File.