我想用一些基本表单数据+一个或多个上传的文件对表单进行反序列化。如果我发送以下请求(使用 Postman 作为 Python 请求代码生成)import requestsurl = "http://127.0.0.1:8000/forms/test/"payload = {'customer_id': '123456789','customer_name': 'Billy Bob'}files = [ ('files', open('/C:/tmp/aaaaa.csv','rb')), ('files', open('/C:/tmp/bbbbb.csv','rb'))]headers= {}response = requests.request("POST", url, headers=headers, data = payload, files = files)print(response.text.encode('utf8'))该代码返回以下响应(我希望它会保存文件)。{ "files": [ "This field is required." ]}楷模from datetime import datetimefrom django.db import modelsclass Mtfar(models.Model): date = models.DateTimeField(auto_now_add=True) customer_id = models.IntegerField() customer_name = models.CharField(max_length=254)class MtfarFile(models.Model): file = models.FileField(blank=False, null=False) mtfar = models.ForeignKey(Mtfar, related_name='files', on_delete=models.CASCADE)序列化器from rest_framework import serializersfrom .models import Mtfar, MtfarFileclass MtfarFileSerializer(serializers.ModelSerializer): class Meta: model = MtfarFile fields = ['file']class MtfarSerializer(serializers.ModelSerializer): files = MtfarFileSerializer(many=True) class Meta: model = Mtfar fields = ['customer_ptid', 'customer_name', 'files']
1 回答
30秒到达战场
TA贡献1828条经验 获得超6个赞
您需要将QueryDict
对象转换为 adict
以支持嵌套序列化,因为 DRFQueryDict
以不同的方式解析 a 。
@api_view(['POST'])
@parser_classes([MultiPartParser])
def post_generic_form(request):
dict_data = {
**request.data.dict(),
**{"files": [{"file": file} for file in request.FILES.getlist('files')]}
}
serializer = MtfarSerializer(data=dict_data)
if serializer.is_valid():
serializer.save()
return Response(status=status.HTTP_201_CREATED)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
添加回答
举报
0/150
提交
取消