To create a file and save it to a model’s FileField with Python Django, we can open the file with open
.
And then we can call save
with the file.
For instance, we write
from django.core.files.base import File
with open('/path/to/file') as f:
self.license_file.save(new_name, File(f))
to open the file at the given path with open
.
Then we create File
object with file handle f
.
And then we call save
with the file name and the File
object we created.
We can also use ContentFile
if we want to create a file without opening a file.
For instance, we write
from django.core.files.base import ContentFile
self.license_file.save(new_name, ContentFile('A string with the file content'))
to create a ContentFile
with a string and save it by calling save
with the file name and the ContentFile
.