Django Rest Framework and file upload

I am trying to create file upload using DRF and jQuery. I googled and found this pattern . I have a similar code for beckand:

class Attachment(BaseModel): file = models.FileField(upload_to=get_photo_path) class AttachmentSerializer(serializers.ModelSerializer): class Meta: model = models.Attachment fields = ('id', 'file') class AttachmentViewSet(viewsets.ModelViewSet): parser_classes = (FileUploadParser, ) serializer_class = serializers.AttachmentSerializer queryset = models.Attachment.objects.all() def pre_save(self, obj): obj.file = self.request.FILES.get('file') 

And tried to translate Angular sample in jQuery

  var fd = new FormData() fd.append('file', file) // file from file-field var reader = new FileReader() $.ajax({ url: 'http://localhost:8001/files/', data: fd, processData: false, contentType: false, type: 'POST' }).done(... 

For some reason, I have an error on the backend when trying to upload a file:

 detail: "FileUpload parse error - none of upload handlers can handle the stream" 
+5
source share
2 answers

Actually the problem is the type of parser. I should use (FormParser, MultiPartParser, ) instead of (FileUploadParser, )

+6
source

By default, Django boot handlers:

 ["django.core.files.uploadhandler.MemoryFileUploadHandler", "django.core.files.uploadhandler.TemporaryFileUploadHandler"] 

and by default there is no FILE_UPLOAD_HANDLERS parameter in the application settings file.

In my case, I excluded MemoryFileUploadHandler and installed

 FILE_UPLOAD_HANDLERS = ["django.core.files.uploadhandler.TemporaryFileUploadHandler", ] 

in the application settings file, and he solved the problem.

+3
source

Source: https://habr.com/ru/post/1235996/


All Articles