How to create and save that file to Django model?

Question:

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

Asked By: Bob

||

Answers:

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.

Answered By: AKX
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.