2

I am trying to upload image to my django website through django rest framework api. but I am getting this error

{ "detail": "Multipart form parse error - Invalid boundary in multipart: None" }

views.py

class UploadPhotoViewSet(APIView):
    parser_classes = (parsers.MultiPartParser, parsers.FormParser)

    def get(self, request,  format=None):
        model_object = Photo.objects.all()
        serializer = PhotoSerializer(model_object, many=True)
        return Response(serializer.data)

    def post(self, request, format=None):
        serializer = PhotoSerializer(data=request.data)

        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

serializers.py

class PhotoSerializer(serializers.ModelSerializer):
    thumbnail = serializers.ImageField(use_url=True)
    source = serializers.ImageField(use_url=True)
    class Meta:
        model = Photo
        fields = '__all__'

model.py

class Photo(models.Model):
    type = models.CharField(max_length=100, default='photo', editable=False)
    project = models.ForeignKey(Project, on_delete=models.CASCADE)
    title = models.CharField(max_length=100)
    description = models.TextField()
    category = models.CharField(max_length=255)

    def upload_thumb_dir(self, filename):
        path = '/media/{}/photos/thumbs/{}'.format(self.project.id, filename)
        return path
    thumbnail = models.ImageField(upload_to=upload_thumb_dir, default='/default/photo.png', blank=True)

    def upload_photo_dir(self, filename):
        path = '/media/{}/photos/{}'.format(self.project.id, filename)
        return path
    source = models.ImageField(upload_to=upload_photo_dir)

    def __str__(self):
        return self.title

enter image description here

2
  • How exactly you upload your image? Via some JS framework? Commented Aug 8, 2017 at 6:30
  • I am using HTTPie – command line HTTP client, and its work fine for update text, read image but not uploading image Commented Aug 8, 2017 at 6:54

1 Answer 1

0

I wasted lot of time using curl and httpie. The best and easy way is use python requests.

I found this way to command line upload image using Django Rest Framework.

import requests
files = {'thumb': open('D:/thumb.jpg', 'rb'), 'preview': open('D:/preview.jpg', 'rb')}
r = requests.put('/path/to/your/django/rest/api', data={'key': value, 'key2': 'value2'}, files=files)
print r.status_code

If you get 201, means you done.

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.