简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM