我正在尝试创建一个接受(键/值)数据和多个文件的端点。用户可以serial连同他的请求一起发送多个文件。上传的文件必须保存FileModel在RequestModel. 问题是当我发送RequestSerializer无法解决的请求时files,我收到有关缺少该files字段的错误。#tests.pydef test_create_request_with_files(self): with tempfile.NamedTemporaryFile() as file: file.write(b"SomeFakeData") file.seek(0) request = { 'files': [file], 'serial': "SomeSerial", } res = self.client.post( '/CreateRequest/', request, format='multipart') print(res.data) self.assertEqual(res.status_code, status.HTTP_201_CREATED)#---------------------------------------------------------------------------# models.pyclass FileModel(models.Model): file = models.FileField(upload_to='upload_files')class RequestModel(models.Model): serial = models.CharField(max_length=100) files = models.ManyToManyField('FileModel', blank=True) def __str__(self): return str(self.id)#---------------------------------------------------------------------------# serializers.pyclass FileSerializer(serializers.ModelSerializer): class Meta: model = FileModel fields = '__all__' read_only_fields = ('id',)class RequestSerializer(serializers.ModelSerializer): files = FileSerializer(many=True) def create(self, validated_data): files = validated_data.pop('files') request_model = RequestModel.objects.create(**validated_data) for file in files: file_model = FileModel.objects.create(file=file) request_model.files.add(file_model) request_model.save() return request_model class Meta: model = RequestModel fields = '__all__' read_only_fields = ('id')#---------------------------------------------------------------------------#views.pyclass RequestList(generics.ListCreateAPIView): queryset = RequestModel.objects.all() serializer_class = RequestSerializer parser_classes = (FormParser, MultiPartParser)
1 回答
叮当猫咪
TA贡献1776条经验 获得超12个赞
这不是 django 的问题。使用时不能传递对象multipart/form-data。列表将转换为[object Object]字符串。而是尝试:file1等file2...
我会使用动态解析器,例如:
count = 1
files = []
f = request.data.get('file{}'.fomat(count))
while f is not None:
files.append(f)
count += 1
f = request.data.get('file{}'.fomat(count))
添加回答
举报
0/150
提交
取消