ImageField but which I adapted for an FileField.Does your app generate some content that is too large or not appropriate for a database? You can store it as a
FileField which points to a file in your MEDIAROOT folder.
How do you upload the generated content to the FileField? Creation is a bit similar to ManyToManyField if you are familiar with using that.- Add the
FileFieldto your model and setblank=True, null=Trueso that you can instantiate it without setting theFileField. - Create the object leaving off the
FileField. Save the instance. - When you retrieve the
FileFieldfrom your model you get aFieldFile(note the word order swap) which allows you to interact with theFileobject (a Django version of a Pythonfileobject). You could save the content to disk then call theFieldFile.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 thatFieldFile.save()content must be adjango.core.files.Fileobject not a Pythonfileobject.
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 FileField to null=True and blank=True is only necessary if you want to upload a file object, otherwise you can pass file name as the FileField when 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.
No comments:
Post a Comment