Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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. 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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading