django - 如何将文件内容传递给序列化程序?
问题描述
我是 django 的新手。我需要实现两个 POST 选项;一个来自 url 参数,另一个来自文件数据。
例如,curl -X POST localhost:8000/api/test?key=value
或curl -X POST -F "file=@myfile.json" localhost:8000/api/test
我在下面进行了测试,但失败了。
class TestEntryView(ListCreateAPIView):
queryset = TestEntry.objects.all().order_by('-id')
parser_classes = (MultiPartParser, FormParser,)
serializer_class = TestEntrySerializer
def perform_create(self, serializer):
if self.request.FILES.get('file'):
file_obj = request.FILES['file']
filename = '/api/mytest/.temp/testfile'
with open(filename, 'wb+') as temp_file:
for chunk in file_obj.chunks():
temp_file.write(chunk)
with open(filename, 'r') as temp_file:
data = json.load(temp_file)
serializer.save(**data)
serializer.save()
=>perform_create()
由于验证字段失败而没有被调用。有没有为此目的推荐的方法?
解决方案
推荐阅读
- python - 对类似的错误消息进行分组 - NLP/机器学习 python
- python - 如何同时使用camelCase和snake_case
- character-encoding - cypress runner 忽略 charset="windows-1252" html 标记
- php - 如何在 jquery 中传递 form_dropdown 的 set_value?
- apache - Apache ModRewrite 语言 .htaccess
- .net - 无法设置 DataGridViewComboBoxColumn 的值而不先显示它
- swift - iPad 上的 Playgrounds 使用此代码崩溃
- c# - C++/CLI 获取“包装器”类对象以显示在 C# 中
- javascript - 您可以使用 WhatsApp API For Business 来验证用户吗?
- javascript - 用鼠标滚轮切换元素