Files and Storages

Updated at 2017-07-07 16:26

Django storage defines an interface for file management. File management mainly consist of serving and uploading files such as avatars. By changing the storage class, you can switch where files are being saved e.g. local file system, AWS S3 or FTP.

Django represents files as django.core.files.File objects. Name of a file must be unique inside a storage; using "directories" and UUIDs is common.

car = Car.objects.get(name="57 Chevy")           # <ImageFieldFile: chevy.jpg>      # cars/chevy.jpg      # /media/cars/chevy.jpg       #
from django.core.files import File

# Creating a Django file object from Python file.
with open('/path/to/', 'w') as f:
    file = File(f)
    file.write('Hello World')

Different files can have different storages. Most of the time you’ll want to use the File object which delegates actions to the proper storage.

from django.db import models
from import FileSystemStorage

avatar_storage = FileSystemStorage(location='/media/avatars')

class Profile(models.Model):
    resume = models.FileField()
    avatar = models.ImageField(storage=avatar_storage)

DefaultStorage is controlled by DEFAULT_FILE_STORAGE setting. Django will use this file storage system if nothing else in specified. By default, default storage is FileSystemStorage which stores files locally using MEDIA_ROOT setting.

# app/settings/
# Here is how to configure
from import DefaultStorage

# And now default storage is S3.
storage = DefaultStorage()

Class reference overview:

from django.core.files.base import ContentFile

file = ContentFile("hello world")       # name of the file including the relative path from MEDIA_ROOT
file.file       # underlying Python file object
for line in file:

# If related to a model.'photo.jpg', contents) # Creates a new file and updates the reference
file.delete()                    # Deletes the file and the reference
from import DefaultStorage

storage = DefaultStorage()
storage.listdir(directory_path)   # Returns directories and files at path.
storage.path(name)                # Returns full local file system path.
storage.url(name)                 # Returns full URL that can be accessed.
storage.get_valid_name(name)      # Returns a new name that is usable.
storage.get_available_name(name)  # Returns a new name that is available.