FileField and FieldFile
Django Modal FileField #
When you access a FileField on a model, you are given an instance of FieldFile as a proxy for accessing the underlying file.
The API of FileField mirrors that of File (File Object in Django), with one key difference: The object wrapped by the class is not necessarily a wrapper around Python’s built-in file object. Instead, it is a wrapper around the result of the Storage.open() method, which may be a File object, or it may be a custom storage’s implementation of the File API.
In addition to the API inherited from File such as read() and write(), FieldFile includes several methods that can be used to interact with the underlying file:
Difference between FileField and FieldFile #
| FileField | FieldFile |
|---|---|
| Model Field | instance returned while accessing model field |
| class FileField( | API is similar to Django File Object |
| upload_to=’’, storage=None, max_length=100, **options) | |
| wrapper around instance of Storage.open() | |
| Storage.open() returns File Object or it’s subclass |
Django Storage class #
doc source The Storage class provides a standardized API for storing files, along with a set of default behaviors that all other storage systems can inherit or override as necessary.
Setting storage class for a FileField #
In Django Settings #
DEFAULT_FILE_STORAGE = 'django.core.files.storage.FileSystemStorage' # default for uploaded or media files
DEFAULT_FILE_STORAGE = 'application_directory.storage_backends.MediaStorage' # custom storage for media files
Per FileField #
from django.conf import settings
from django.db import models
from .storages import MyLocalStorage, MyRemoteStorage
def select_storage():
return MyLocalStorage() if settings.DEBUG else MyRemoteStorage()
class MyModel(models.Model):
my_file = models.FileField(storage=select_storage)
open(name, mode=‘rb’) method #
- Opens the file given by name. Note that although the returned file is guaranteed to be a File object, it might actually be some subclass.
- In the case of remote file storage this means that reading/writing could be quite slow, so be warned.
Warning #
Two methods of this class, save() and delete(), default to saving the model object of the associated FieldFile in the database.
Django Model FieldFile.open(mode=‘rb’) #
Opens or reopens the file associated with this instance in the specified mode. Unlike the standard Python open() method, it doesn’t return a file descriptor.
Since the underlying file is opened implicitly when accessing it, it may be unnecessary to call this method except to reset the pointer to the underlying file or to change the mode.
FieldFile.close() #
Behaves like the standard Python file.close() method and closes the file associated with this instance.
Django model FieldFile.save(name, content, save=True) #
This method takes a filename and file contents and passes them to the storage class for the field, then associates the stored file with the model field. If you want to manually associate file data with FileField instances on your model, the save() method is used to persist that file data.
Takes two required arguments:
name which is the name of the file, and
content which is an object containing the file’s contents.* - 1. must be the instance of `django.core.files.File` (*File Object in Django
The optional save argument controls whether or not the model instance is saved after the file associated with this field has been altered. Defaults to True.
Note that the content argument should be an instance of django.core.files.File, not Python’s built-in file object. You can construct a File from an existing Python file object like this:
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 you can construct one from a Python string like this:
from django.core.files.base import ContentFile
myfile = ContentFile("hello world")
# from Django's documentation, see above ref
from django.core.files.base import ContentFile
content = ContentFile("esta frase está en español")
content = ContentFile(b"these are bytes")
car.photo.save('myphoto.jpg', content, save=False)
car.save()
# are equivalent to:
car.photo.save('myphoto.jpg', content, save=True)
# Note that the content argument must be an instance of either File or of a subclass of File, such as ContentFile.
For more information, see Managing files.
FieldFile.delete(save=True) #
Deletes the file associated with this instance and clears all attributes on the field. Note: This method will close the file if it happens to be open when delete() is called.
The optional save argument controls whether or not the model instance is saved after the file associated with this field has been deleted. Defaults to True.
Note that when a model is deleted, related files are not deleted. If you need to cleanup orphaned files, you’ll need to handle it yourself (for instance, with a custom management command that can be run manually or scheduled to run periodically via e.g. cron).