gpt4 book ai didi

python - 属性错误 : 'file' object has no attribute '_committed'

转载 作者:太空宇宙 更新时间:2023-11-03 15:02:12 30 4
gpt4 key购买 nike

我的模型中有一个 DjangoFileField。我正在尝试将音频类型从该 FielField 转换为 mp3,然后再次尝试保存它。但是在转换类型并使用 pydub 导出它之后,它返回以下错误

AttributeError: 'file' object has no attribute '_committed'

我的代码是这样的

def get_from_function(AudioSegment, format):

form = "from_{0}".format(format)
print form
if hasattr(AudioSegment, form):
return getattr(AudioSegment, form)
return None


audio = request.FILES.get('audio', None)
if audio:
name_list = audio.name.rsplit(".")
voice_format =name_list[1]
from_format = get_from_function(AudioSegment, voice_format)
if from_format and callable(from_format):
sound = from_format(audio)
audio = sound.export("media/{0}".format(name_list[0]), mp3")

当我打印 audio 时,它会打印

<open file 'media/barsandtone', mode 'wb+' at 0x7f771e5e2f60>

当我打印它打印的文件类型时

<type 'file'>

但是当我将音频字段分配给像

这样的 django 模型时
Mymodel.objects.create(audio=audio)

它给出了错误

AttributeError at /create/
'file' object has no attribute '_committed'

将导出的文件保存到django模型中的正确方法是什么

最佳答案

django 通常需要一个 ContentFile 来传递数据流,而且它不像通常将参数传递给模型那样工作。正确的做法如下

from django.core.files.base import ContentFile
[...]
mymodel = Mymodel()
mymodel.audio.save(audio.name, ContentFile(audio.read()))

不要忘记将流传递给 ContentFile。如果您传递 ContentFile(audio) Django 不会引发任何错误,但在这种情况下您不会保存文件内容..

关于python - 属性错误 : 'file' object has no attribute '_committed' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36610146/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com