这是我的模型。我想要做的是生成一个新文件并在保存模型实例时覆盖现有文件:
class Kitten(models.Model):
claw_size = ...
license_file = models.FileField(blank=True, upload_to='license')
def save(self, *args, **kwargs):
#Generate a new license file overwriting any previous version
#and update file path
self.license_file = ???
super(Request,self).save(*args, **kwargs)
我看到很多关于如何上传文件的文档。但是如何生成文件,将其分配给模型字段并让 Django 将其存储在正确的位置?
最佳答案
你想看看FileField and FieldFile在 Django 文档中,尤其是 FieldFile.save() .
基本上,声明为 FileField
的字段在访问时会为您提供一个类 FieldFile
的实例,该实例为您提供与底层文件交互的多种方法。所以,你需要做的是:
self.license_file.save(new_name, new_contents)
其中 new_name
是您希望分配的文件名,new_contents
是文件的内容。请注意,new_contents
必须是 django.core.files.File
或 django.core.files.base.ContentFile
的实例(参见给出的链接到手册了解详细信息)。
这两种选择归结为:
from django.core.files.base import ContentFile, File
# Using File
with open('/path/to/file') as f:
self.license_file.save(new_name, File(f))
# Using ContentFile
self.license_file.save(new_name, ContentFile('A string with the file content'))
关于python - Django - 如何创建文件并将其保存到模型的 FileField?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7514964/