can't uplpoad photos in multipart form in django rest framework

4.3k views Asked by At

I hsve a project where user can upload multiple photos when creating a announcement, when sending request from postman using form-data the announcement is added successfully but the image is not uploaded, when using raw Json with content type setting to:multipart/form-data, i got the following error:

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

when sending the following request from browsable API:

{
    "name": "tractor",
    "address": "any",
    "price": 100,
    "author": 17,
    "photo": [
        {
            "name": "tractor",
            "image": "/C:/Users/Admin/Downloads/marteau.jpg"
        }
    ]
}

I got the following error:

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

He is my code:

Models.py

class Photo(models.Model):
    name = models.CharField(max_length=100)
    image = models.ImageField(upload_to=nameFile, blank=True, null=True)

  
class Announcement(models.Model):
    author = models.ForeignKey(
        User, on_delete=models.CASCADE,  related_name='announcements')
    name = models.CharField(max_length=100)
    address = models.CharField(max_length=100)
    price = models.FloatField(blank=True, null=True)
    description = models.TextField(blank=True, null=True)
    rating = models.FloatField(blank=True, null=True)
    date = models.DateTimeField(auto_now_add=True)
    photo = models.ManyToManyField(Photo, blank=True)

Views.py

class AnnouncementCreate(CreateAPIView):
    queryset = models.Announcement.objects.all()
    serializer_class = AnnouncementSerializer
    parser_classes = (FormParser,MultiPartParser)
    def perform_create(self, serializer):
        serializer.save(author=self.request.user)

class PhotoViewSet(ListAPIView):

    queryset = models.Photo.objects.all()
    serializer_class = PhotoSerializer

    def post(self, request, *args, **kwargs):
        file = request.data.get('image')
        image = models.Photo.objects.create(image=file)
        return HttpResponse(json.dumps({'message': "Uploaded"}), status=200)

Serializers.py

class AnnouncementSerializer(WritableNestedModelSerializer, serializers.ModelSerializer):
    parameters = ParameterSerializer(many=True, required=False)
    photo = PhotoSerializer(many=True, required=False)
class Meta:
        model = Announcement
        fields = ['id', 'name', 'address', 'date',
                  'price', 'description', 'author', 'parameters', 'photo']

class PhotoSerializer(serializers.ModelSerializer):
    class Meta:
        model = Photo
        fields = ('name', 'image')


2

There are 2 answers

0
Mahmoud Adel On

I have opened an issue before asking about this and the response I got was, sadly, DRF doesn't support nested writable serializer with multipart/form-data.

Here is my issue: https://github.com/encode/django-rest-framework/issues/7262

If you can get rid of nested serializer then you will be able to normally upload a file with multipart/form-data, otherwise, you have to use application/json and encode your file as a base64 string so you will be able to upload a file with nested serializers.

1
Reil Waystation On

you have to use MultiPartParser because the default parser in DRF is Json parser you're not sending JSON but you are sending binary

https://www.django-rest-framework.org/api-guide/parsers/