[英]How to create and save that file to Django model?
I want to create a file and save it to Django model within a view without creating any temporary files or anything like that.我想在视图中创建一个文件并将其保存到 Django model 而不创建任何临时文件或类似的东西。 I plan to write a.txt file that contains information and I want to save the.txt file in the Django model.
我打算写一个包含信息的.txt文件,我想将.txt文件保存在Django model中。
Does anyone know how to do this?有谁知道如何做到这一点?
Thank you谢谢
Yes – ContentFile .是的—— 内容文件。
Assuming a model假设 model
class Blah(models.Model):
file = models.FileField(...)
you can use您可以使用
from django.core.files.base import ContentFile
def view(request):
content = b"Bla bla bla."
file = ContentFile(content, name="my_file.txt")
Blah.objects.create(file=file)
to create a model with something assigned to its file field without having had a file on disk.创建一个 model 并为其文件字段分配一些内容,而磁盘上没有文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.