ImageFieldbut which I adapted for an
Does your app generate some content that is too large or not appropriate for a database? You can store it as a
FileFieldwhich points to a file in your
MEDIAROOTfolder. How do you upload the generated content to the
FileField? Creation is a bit similar to
ManyToManyFieldif you are familiar with using that.
- Add the
FileFieldto your model and set
blank=True, null=Trueso that you can instantiate it without setting the
- Create the object leaving off the
FileField. Save the instance.
- When you retrieve the
FileFieldfrom your model you get a
FieldFile(note the word order swap) which allows you to interact with the
Fileobject (a Django version of a Python
fileobject). You could save the content to disk then call the
FieldFile.save()method, but you can skip this unnecessary step. Let's assume the content can be serialized as a JSON object. The following code will upload the content to Django. Also note that
FieldFile.save()content must be a
django.core.files.Fileobject not a Python
from StringIO import StringIO import json from django.core.files import File f = StringIO(json.dumps(my_content, indent=2, sort_keys=True)) try: my_model_object.my_file_field.save('my_file_name.json', File(f)) # `FieldFile.save()` saves the instance of the model by default finally: f.close() # `StringIO` has no `__exit__` method to use `with`Setting the
blank=Trueis only necessary if you want to upload a file object, otherwise you can pass file name as the
FileFieldwhen you construct the database object. EG:
my_model_object(my_char_field='some other model fields', my_file_field='my_file_field.json')This will upload
'my_file_field.json'from disk if it is a valid path.