如何将生成的文件与Django模型相关联

时间:2016-03-26 20:25:48

标签: django file

我想创建一个文件并将其与我模型的FileField相关联。这是我的简化尝试:

#instantiate my form with the POST data
form = CSSForm(request.POST)
#generate a css object from a ModelForm
css = form.save(commit=False)
#generate some css:
css_string = "body {color: #a9f;}"
#create a css file:
filename = "myfile.css"
#try to write the file and associate it with the model
with open(filename, 'wb') as f:
    df = File(f) #create django File object
    df.write(css_string)
    css.css_file = df
css.save()

save()的调用会引发"seek of closed file"异常。如果我将save()移动到with块,则会产生不受支持的操作"read"。目前,文件正在我的媒体目录中创建,但是为空。如果我只使用css_string呈现HttpResponse,那么我会看到预期的css。

The docs似乎没有关于如何链接生成的文件和数据库字段的示例。我该怎么做?

1 个答案:

答案 0 :(得分:2)

Django FileField可以是django.core.files.File,它是一个文件实例或django.core.files.base.ContentFile,它将字符串作为参数并组成ContentFile。由于您已经将文件内容作为字符串,因此ContentFile之类的声音是可行的方式(我无法测试它但它应该可以工作):

from django.core.files.base import ContentFile

# create an in memory instance
css = form.save(commit=False)
# file content as string
css_string = "body {color: #a9f;}"
# create ContentFile instance
css_file = ContentFile(css_string)
# assign the file to the FileField
css.css_file.save('myfile.css', css_file)
css.save()

检查django doc FileField details