django 上传文件

前后端分离下django 框架上传文件实现方式

实现方式一,通过model字段FileFiled()来实现

  • model类

class Report(models.Model):
    p_id = models.PositiveIntegerField('病人ID')
    file = models.FileField(upload_to='uploads/report/%Y/%m/%d/')

    def __str__(self):
        return str(self.file)
  • serializer 类

class ReportSerializer(serializers.ModelSerializer):
    file = serializers.FileField()

    class Meta:
        model = Report
        fields = '__all__'
  • 视图类

class ReportUploadView(generics.CreateAPIView):
    # queryset = Report.objects.all()
    serializer_class = ReportSerializer
    parser_classes = [MultiPartParser, FormParser]

    def post(self, request, *args, **kwargs):
        print('Upload', request.data['p_id'])
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            print(serializer.data)
            serializer.data.pop('file')
            # serializer.data['file'] = parse.unquote(serializer.data.pop('file'))
            print('上传文件中', serializer.data)
            return APIResponse(status.HTTP_201_CREATED, serializer.data)
        else:
            return APIResponse(status.HTTP_400_BAD_REQUEST, serializer.errors)


来自为知笔记(Wiz)


posted on 2023-08-21 11:56  白衣风云  阅读(13)  评论(0编辑  收藏  举报

导航