4

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

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

1 Comment

is it the same url when using a router ?

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.