编程语言
首页 > 编程语言> > python-AttributeError:“文件”对象没有属性“ _committed”

python-AttributeError:“文件”对象没有属性“ _committed”

作者:互联网

我的模型中有一个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")

当我打印音频时,它会打印

<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不会引发任何错误,但在那种情况下,您将不会保存文件内容.

标签:filefield,django-file-upload,python,django
来源: https://codeday.me/bug/20191027/1942131.html