如何使用 Django Rest Framework 在单个请求中反序列化多个文件和表单数据?

我想用一些基本表单数据+一个或多个上传的文件对表单进行反序列化。


如果我发送以下请求(使用 Postman 作为 Python 请求代码生成)


import requests


url = "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 datetime

from django.db import models


class 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 serializers

from .models import Mtfar, MtfarFile


class 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']


DIEA
浏览 171回答 1
1回答

30秒到达战场

您需要将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)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python