[Django]-Save the file for a FileField without a form

6👍

Well, you are most likely need to use FieldFile object, which defines the content of a FileField to save the file. To make a FieldFile, you could either use a file descriptor in your file system or a string representing the file content. Django doc has good explanation about field.save() method, quoting:

from django.core.files import File
# Open an existing file using Python's built-in open()
f = open('/path/to/hello.world')
myfile = File(f)

or

from django.core.files.base import ContentFile
myfile = ContentFile("hello world")

Then do

obj.field.save('filename', myfile)

Django doc says it all.

Leave a comment