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
JavaScript
x
3
1
class Blah(models.Model):
2
file = models.FileField( )
3
you can use
JavaScript
1
7
1
from django.core.files.base import ContentFile
2
3
def view(request):
4
content = b"Bla bla bla."
5
file = ContentFile(content, name="my_file.txt")
6
Blah.objects.create(file=file)
7
to create a model with something assigned to its file field without having had a file on disk.