I am using Django-rest Framework for a project in which I am uploading the images to amazon s3 from my local system. This I am doing using the Html form which works fine.
This is the model image.
models.py
class Image(models.Model):
image_meta = models.ForeignKey('Image_Meta',on_delete=models.CASCADE,)
image = models.ImageField(upload_to='images-data')
order = models.IntegerField()
version = models.CharField(max_length=10)
But when I try to upload the image as raw data I get an error.
I want to know how can I do that. I tried to enter the location of the file in the local system for image field without any success.
What am I doing wrong here or am I missing something here?
The views.py file is below:
class ImageList(APIView):
parser_classes = (JSONParser, )
def get(self, request, format=None):
images = Image.objects.all()
serializer = ImageSerializer(images, many=True)
return Response(serializer.data)
def post(self, request, format=None):
serializer = ImageSerializer(data=request.data , files=request.FILES)
print serializer
if serializer.is_valid():
serializer.save()
return Response({'received data': request.data})
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
serializer.py
class ImageSerializer(serializers.ModelSerializer):
class Meta:
model = Image
field = ('id', 'image_path' , 'order' , 'version')
In your api view class use
Your uploaded file be available as a file object in the request.data dictionary with the key as 'file'.
Your front end client will send the file data in the key "file".
Read more about the FileUploadParser here: http://www.django-rest-framework.org/api-guide/parsers/#fileuploadparser
code example:
Here in the model I have taken the field image as a path field and not as a ImageField.