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
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 theMultiPartParser
instead
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With