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

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将其存储在正确的位置呢?

推荐答案

你想看看Django文档中的FileField and FieldFile,特别是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的实例(有关详细信息,请参阅手册的给定链接).

这两种 Select 归结为:

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'))

Django相关问答推荐

从Azure Web应用服务器上的cron任务的虚拟环境加载变量

如何在Django CMS中更新上下文

Django: 无法将我的 comments 关联到特定产品

Django 相当于子查询

在 Django 4.1 中提交表单之前显示数据

无法创建超级用户,因为 Django 中的一列(外键)不能为空

root urls.py 是 Django 中的 config/urls.py 吗?

DecimalField 验证错误,返回不正确的值 Django

Django ORM:获取每个类别的月平均价格

当我告诉它时,如何使用 Django 的记录器来记录回溯?

如何查看 Django 调试工具栏?

django.request 记录器没有传播到根目录?

如何在 Django 中向 ChoiceField 添加class?

virtualenv(python3.4), pip install mysqlclient 错误

使用 lambda 作为属性的默认值时,Django 1.7.1 Makemigrations 失败

settings.DATABASES 配置不正确使用 django 1.4 执行 syncdb 时出错

Django:验证上传文件的文件类型

django - 使用 get_or_create 自动创建用户时设置用户权限

在 Django 中的字段中添加额外的约束

在 Django 中查询 top x 元素