我想用一些基本表单数据+一个或多个上传的文件对表单进行反序列化。
如果我发送以下请求(使用 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']
30秒到达战场
相关分类