Django - 如何创建文件并将其保存到模型的 FileField? [英] Django - how to create a file and save it to a model's FileField?

查看:39
本文介绍了Django - 如何创建文件并将其保存到模型的 FileField?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Here's my model. What I want to do is generate a new file and overwrite the existing one whenever a model instance is saved:

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

I see lots of documentation about how to upload a file. But how do I generate a file, assign it to a model field and have Django store it in the right place?

推荐答案

你想看看 FileField 和 FieldFile 在 Django 文档中,尤其是 FieldFile.save().

You want to have a look at FileField and FieldFile in the Django docs, and especially FieldFile.save().

基本上,声明为 FileField 的字段在访问时会为您提供一个 FieldFile 类的实例,它为您提供多种与底层文件交互的方法.所以,你需要做的是:

Basically, a field declared as a FileField, when accessed, gives you an instance of class FieldFile, which gives you several methods to interact with the underlying file. So, what you need to do is:

self.license_file.save(new_name, new_contents)

其中 new_name 是您希望分配的文件名,new_contents 是文件的内容.请注意,new_contents 必须是 django.core.files.Filedjango.core.files.base.ContentFile 的实例(请参阅给定的有关详细信息的手册链接).

where new_name is the filename you wish assigned and new_contents is the content of the file. Note that new_contents must be an instance of either django.core.files.File or django.core.files.base.ContentFile (see given links to manual for the details).

这两个选择归结为:

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 - 如何创建文件并将其保存到模型的 FileField?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆