I want to create a file and save it to Django model within a view without creating any temporary files or anything like that. I plan to write a .txt file that contains information and I want to save the .txt file in the Django model.
Does anyone know how to do this?
Thank you
Advertisement
Answer
Yes – ContentFile.
Assuming a 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.