Managing files

    By default, Django stores files locally, using the MEDIA_ROOT and settings. The examples below assume that you’re using these defaults.

    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.

    When you use a or ImageField, Django provides a set of APIs you can use to deal with that file.

    Consider the following model, using an to store a photo:

    Any Car instance will have a photo attribute that you can use to get at the details of the attached photo:

    1. >>> car = Car.objects.get(name="57 Chevy")
    2. >>> car.photo
    3. <ImageFieldFile: cars/chevy.jpg>
    4. >>> car.photo.name
    5. 'cars/chevy.jpg'
    6. >>> car.photo.path
    7. '/media/cars/chevy.jpg'
    8. >>> car.photo.url
    9. '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.

    Note

    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.

    For example, you can change the file name by setting the file’s name to a path relative to the file storage’s location ( if you are using the default FileSystemStorage):

    1. >>> import os
    2. >>> from django.conf import settings
    3. >>> initial_path = car.photo.path
    4. >>> car.photo.name = 'cars/chevy_ii.jpg'
    5. >>> new_path = settings.MEDIA_ROOT + car.photo.name
    6. >>> # Move the file on the filesystem
    7. >>> os.rename(initial_path, new_path)
    8. >>> car.save()
    9. '/media/cars/chevy_ii.jpg'
    10. >>> car.photo.path == new_path
    11. True

    Note

    While non-image data attributes, such as height, , and size are available on the instance, the underlying image data cannot be used without reopening the image. For example:

    1. >>> from PIL import Image
    2. >>> car = Car.objects.get(name='57 Chevy')
    3. >>> car.photo.width
    4. 191
    5. >>> car.photo.height
    6. 287
    7. >>> image = Image.open(car.photo)
    8. # Raises ValueError: seek of closed file.
    9. >>> car.photo.open()
    10. <ImageFieldFile: cars/chevy.jpg>
    11. >>> image = Image.open(car.photo)
    12. >>> image
    13. <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 file object:

    1. >>> from django.core.files import File
    2. # Create a Python file object using open()
    3. >>> f = open('/path/to/hello.world', 'w')
    4. >>> myfile = File(f)

    Now you can use any of the documented attributes and methods of the class.

    Be aware that files created in this way are not automatically closed. The following approach may be used to close files automatically:

    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:

    1. 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.

    See below for details of the built-in default file storage system, and see How to write a custom storage class 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:

    1. >>> from django.core.files.base import ContentFile
    2. >>> path = default_storage.save('path/to/file', ContentFile(b'new content'))
    3. >>> path
    4. 'path/to/file'
    5. >>> default_storage.size(path)
    6. 11
    7. >>> default_storage.open(path).read()
    8. b'new content'
    9. >>> default_storage.delete(path)
    10. >>> default_storage.exists(path)
    11. False

    See for the file storage API.

    Django ships with a django.core.files.storage.FileSystemStorage class which implements basic local filesystem file storage.

    For example, the following code will store uploaded files under /media/photos regardless of what your setting is:

    Custom storage systems work the same way: you can pass them in as the storage argument to a .

    You can use a callable as the storage parameter for or ImageField. This allows you to modify the used storage at runtime, selecting different storages for different environments, for example.

    Your callable will be evaluated when your models classes are loaded, and must return an instance of .

    For example:

    1. from django.conf import settings
    2. from django.db import models
    3. from .storages import MyLocalStorage, MyRemoteStorage
    4. def select_storage():
    5. return MyLocalStorage() if settings.DEBUG else MyRemoteStorage()
    6. class MyModel(models.Model):