Django FileField:如何设置默认值(自动创建空文件)?
我有一个这样的模型:
class MyModel(models.Model):
name = models.CharField(max_length=255)
code = models.FileField()
当提交一个新的 MyModel 时,我希望允许 code 字段留空,在这种情况下,我需要 Django 创建一个空文件(任意姓名)。
问题是:正确的做法是什么?
我在文档中找不到任何相关内容,因此我正在考虑手动编辑 request.FILES,然后再将其提供给 MyModelForm(),但这对我来说看起来像是一个肮脏的黑客......有什么想法吗?
谢谢。
I've got a model like this:
class MyModel(models.Model):
name = models.CharField(max_length=255)
code = models.FileField()
When a new MyModel is submitted, I want to allow for the code field to be left empty, in which case I need Django to create an empty file (with arbitrary name).
Question is: what is the right way to do it?
I couldn't find anything related in the docs, so I was looking at manually editing request.FILES before feeding it to MyModelForm(), but this looks like a dirty hack to me... Any ideas?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我会将代码输入存储在 CharField 中,然后创建一个单独的函数来访问模型,如果代码不包含任何有害方法,则将其写入文件。
这负责创建文件(因为空白 CharField 将简单地输出到空文件)并允许委派给安全检查器。您的设置将如下所示:
模型:
视图:
编辑
新视图:
I would store the code input in a CharField and then create a separate function that accesses the model and if the code does not contain any harmful methods it is then written to a file.
This takes care of creating the file (as a blank CharField will simply be outputted to an empty file) and allows for delegation to a security checker. Your setup would then look something like the following:
Model:
View:
Edit
New view:
只需将字段设置为允许空和空白即可。这将使该字段成为可选字段。
Just set the field to allow null and blank. This will make the field optional.