python - Django - 如何创建文件并将其保存到模型的 FileField?

标签 python django django-models

这是我的模型。我想要做的是生成一个新文件并在保存模型实例时覆盖现有文件:

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.Filedjango.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/

相关文章:

python - 如何在我的版本控制系统中安全地保存我的 key 和密码?

模型中 _set 的 Django 管理器

python - Django - 强制执行 ManyToManyField 唯一项

python - 使用 Sympy 集成

iterator - 用于容器的 Itertools

python - python "in"语句是否自动返回为真

python - Django 单元测试客户端登录 : fails in test suite, 但不在 Shell 中

django - 使用模型的 __unicode__ 作为管理表单中的搜索字段

Django:如何自动递增可以具有多个相同值的字段

python - Anaconda Jupyter Notebook 突然无法启动内核