ruk·si

Django
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")
car.photo           # <ImageFieldFile: 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
from django.core.files import File

# Creating a Django file object from Python file.
with open('/path/to/hello.world', '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 django.core.files.storage 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/__init__.py
# Here is how to configure https://github.com/etianen/django-s3-storage
DEFAULT_FILE_STORAGE = "django_s3_storage.storage.S3Storage"
STATICFILES_STORAGE = "django_s3_storage.storage.StaticS3Storage"
from django.core.files.storage import DefaultStorage

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

Class reference overview:

from django.core.files.base import ContentFile

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

# If related to a model.
file.save('photo.jpg', contents) # Creates a new file and updates the reference
file.delete()                    # Deletes the file and the reference
from django.core.files.storage 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_accessed_time(name)
storage.get_created_time(name)
storage.get_modified_time(name)
storage.delete(name)
storage.exists(name)
storage.get_valid_name(name)      # Returns a new name that is usable.
storage.get_available_name(name)  # Returns a new name that is available.

Source