Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File Upload handling in Django rest framework

I am trying to add a filefield in my django models but I am not sure how to handle the files coming from React Front-end.

Models.py

class Product(models.Model):
    
    name = models.CharField(max_length=500, default=0)
    short_code = models.CharField(max_length=500, default=0,unique=True)
    document = models.FileField(upload_to='products/', null=True, blank=True)
    owner = models.ForeignKey(User, on_delete=models.CASCADE)

Serializer.py

class ProductSerializer(serializers.ModelSerializer):

    class Meta:
        model = Product
        fields = "__all__"

When the File is uploaded from Frontend it gives the following error in Network

{"detail":"Unsupported media type "multipart/form-data boundary=967753268136369" in request."}

I have gone through the documentation of DRF and I am sure I need to implement MultiParser in it but I am not sure how. Also Is there a better way to handle "File Handling"? I am using Ant Design File Upload in the application

like image 398
Rahul Sharma Avatar asked Sep 17 '25 14:09

Rahul Sharma


1 Answers

Specify the MultiPartParser in your generic views or viewsets, then the media-type is dynamically set to multipart/form-data by the parser, this parses multipart HTML form content, which supports file upload

from rest_framework.parsers import MultiPartParser

class ProductViewSet(viewsets.ModelViewSet):
    parser_classes = [MultiPartParser]
    ...

Or you could make use of the FileUploadParser as described in DRF Doc as follows:

class FileUploadView(views.APIView):
    parser_classes = [FileUploadParser]

    def put(self, request, filename, format=None):
        file_obj = request.data['file']
        # ...
        # do some stuff with uploaded file
        # ...
        return Response(status=204)

# urls.py
urlpatterns = [
    # ...
    url(r'^upload/(?P<filename>[^/]+)$', FileUploadView.as_view())
]

Note: this way, you have to manually set request header Content-Disposition: attachment; filename=upload.jpg

The FileUploadParser is for usage with native clients that can upload the file as a raw data request. For web-based uploads, or for native clients with multipart upload support, you should use the MultiPartParser instead

like image 98
minglyu Avatar answered Sep 19 '25 05:09

minglyu