However, Django provides ways to write custom file storage systems that allow you to completely customize where and how Django stores files. The second half of this document describes how these storage systems work.
Using files in models¶
Consider the following model, using an
store a photo:
from django.db import models class Car(models.Model): name = models.CharField(max_length=255) price = models.DecimalField(max_digits=5, decimal_places=2) photo = models.ImageField(upload_to='cars')
Car instance will have a
photo attribute that you can use to get at
the details of the attached photo:
>>> car = Car.objects.get(name="57 Chevy") >>> car.photo <ImageFieldFile: cars/chevy.jpg> >>> car.photo.name 'cars/chevy.jpg' >>> car.photo.path '/media/cars/chevy.jpg' >>> car.photo.url 'http://media.example.com/cars/chevy.jpg'
This object –
car.photo in the example – is a
File object, which means
it has all the methods and attributes described below.
The file is saved as part of saving the model in the database, so the actual file name used on disk cannot be relied on until after the model has been saved.
>>> import os >>> from django.conf import settings >>> initial_path = car.photo.path >>> car.photo.name = 'cars/chevy_ii.jpg' >>> new_path = settings.MEDIA_ROOT + car.photo.name >>> # Move the file on the filesystem >>> os.rename(initial_path, new_path) >>> car.save() >>> car.photo.path '/media/cars/chevy_ii.jpg' >>> car.photo.path == new_path True
ImageField non-image data attributes,
size are available on the instance,
the underlying image data cannot be used without reopening the image. For
>>> from PIL import Image >>> car = Car.objects.get(name='57 Chevy') >>> car.photo.width 191 >>> car.photo.height 287 >>> image = Image.open(car.photo) # Raises ValueError: seek of closed file. >>> car.photo.open() <ImageFieldFile: cars/chevy.jpg> >>> image = Image.open(car.photo) >>> image <PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=191x287 at 0x7F99A94E9048>
Internally, Django uses a
django.core.files.File instance any time it
needs to represent a file.
Most of the time you’ll use a
File that Django’s given you (i.e. a file
attached to a model as above, or perhaps an uploaded file).
If you need to construct a
File yourself, the easiest way is to create one
using a Python built-in
>>> from django.core.files import File # Create a Python file object using open() >>> f = open('/path/to/hello.world', 'w') >>> myfile = File(f)
Now you can use any of the documented attributes and methods
Be aware that files created in this way are not automatically closed. The following approach may be used to close files automatically:
>>> from django.core.files import File # Create a Python file object using open() and the with statement >>> with open('/path/to/hello.world', 'w') as f: ... myfile = File(f) ... myfile.write('Hello World') ... >>> myfile.closed True >>> f.closed True
Closing files is especially important when accessing file fields in a loop over a large number of objects. If files are not manually closed after accessing them, the risk of running out of file descriptors may arise. This may lead to the following error:
OSError: [Errno 24] Too many open files
Behind the scenes, Django delegates decisions about how and where to store files to a file storage system. This is the object that actually understands things like file systems, opening and reading files, etc.
Django’s default file storage is given by the
setting; if you don’t explicitly provide a storage system, this is the one that
will be used.
See below for details of the built-in default file storage system, and see Writing a custom storage system for information on writing your own file storage system.
Though most of the time you’ll want to use a
File object (which delegates to
the proper storage for that file), you can use file storage systems directly.
You can create an instance of some custom file storage class, or – often more
useful – you can use the global default storage system:
>>> from django.core.files.base import ContentFile >>> from django.core.files.storage import default_storage >>> path = default_storage.save('path/to/file', ContentFile(b'new content')) >>> path 'path/to/file' >>> default_storage.size(path) 11 >>> default_storage.open(path).read() b'new content' >>> default_storage.delete(path) >>> default_storage.exists(path) False
See File storage API for the file storage API.
The built-in filesystem storage class¶
Django ships with a
which implements basic local filesystem file storage.
For example, the following code will store uploaded files under
/media/photos regardless of what your
MEDIA_ROOT setting is:
from django.core.files.storage import FileSystemStorage from django.db import models fs = FileSystemStorage(location='/media/photos') class Car(models.Model): ... photo = models.ImageField(storage=fs)