简体   繁体   中英

Django-Rest-Framework File Upload

I am using Django Rest Framework to upload a file My view file looks like this:

class FileViewSet(viewsets.ModelViewSet):
    queryset = Files.objects.all()
    serializer_class = FilesSerializer
    #+++++++++++++++++++++++++++++++++++++
    parser_classes = (MultiPartParser, FormParser)

    def post(self, request, *args, **kwargs):
        serializer = FilesSerializer(data=request.data)
        if serializer.is_valid():
        serializer.save()
            return Response(serializer.data, status=HTTP_201_CREATED)
        else:
            return Response(serializer.error, status=HTTP_400_BAD_REQUEST)

My view works well with file upload even if there is no bottom part of the comment. So why should I use the code under the comment?

I used the translator. Please understand if there is a mistake.

Your code is working without the post function because ModelViewSet class(ie the one you inherited in your FileViewSet) already has implementations of various actions like list(),create(), retrieve(), update() etc.

So when you are hitting post request for uploading the file, create() action gets called automatically and will save the file by taking values provided by you in class variables like serializer_class,parser_classes etc.

Read more about ModelViewSet :

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM