7

I am working with an app using Django Rest Framework.

models.py

class Image(models.Model):
    image_meta = models.ForeignKey('Image_Meta',on_delete=models.CASCADE,)
    image_path = models.URLField(max_length=200)
    order = models.IntegerField()
    version = models.CharField(max_length=10)

serializers.py

class ImageSerializer(serializers.ModelSerializer):
    class Meta:
        model = Image
        field = ('id', 'image_path' , 'order' , 'version')

views.py

class ImageList(generics.ListCreateAPIView):
    queryset = Image.objects.all()
    serializer_class = ImageSerializer

class ImageDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = Image.objects.all()
    serializer_class = ImageSerializer

url patterns

url(r'^image/$',views.ImageList.as_view(),name='image_list'),
url(r'^image/(?P<pk>[0-9]+)/$',views.ImageDetail.as_view(),name='image_detail')

This is just a part of the whole system. I want to upload images using the RESTAPI and then upload it to amazon s3 and from there get the url and store it in the image_path field of the model Image. I have seen previous solutions for uploading files using REST (like this)but nothing worked for my case. Can someone suggest how can I do that?

the_unknown_spirit
  • 2,518
  • 7
  • 34
  • 56

2 Answers2

0

We know that images/files are uploaded using multipart/form-data. By Default DRF don't parse multipart data.

To make drf parse multipart data you have to tell DRP view to use MultiPartParser parser.

from rest_framework.parsers import MultiPartParser
class ImageList(generics.ListCreateAPIView):
    ...
    ...     
    parser_classes = (MultiPartParser)
    ...

I'll recommend to have a imagefield in your serializer for image field, and process it there to upload to amazon and populate URLField

Community
  • 1
  • 1
varnothing
  • 1,269
  • 1
  • 17
  • 30
0

Well I finally have figured out how this can be done. I changed the image_path to ImageField as suggested by Saurabh Goyal. I used this code:

class Image(models.Model):
    image_meta = models.ForeignKey('Image_Meta',on_delete=models.CASCADE,)
    image_path = models.ImageField(upload_to='images-data')
    order = models.IntegerField()
    version = models.CharField(max_length=10)

N provided my amazon s3 bucket details as in the local_settings.py file as :

AWS_S3_ACCESS_KEY_ID = "Access_key_id"
AWS_S3_SECRET_ACCESS_KEY = "secret_access_key"
AWS_STORAGE_BUCKET_NAME = "bucket_name"

and added this to settings.py :

DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage'

and voila!! It worked. I hope this helps someone stuck at the same problem as me.

the_unknown_spirit
  • 2,518
  • 7
  • 34
  • 56