Writing a custom storage system

    • Your custom storage system must be a subclass of:
    • Django must be able to instantiate your storage system without any arguments.This means that any settings should be taken from django.conf.settings:
    1. from django.conf import settings
    2. from django.core.files.storage import Storage
    3.  
    4. class MyStorage(Storage):
    5. def __init__(self, option=None):
    6. if not option:
    7. ...
    • Your storage class must implement the _open() and methods, along with any other methods appropriate to your storage class. Seebelow for more on these methods.

    In addition, if your class provides local file storage, it must overridethe path() method.

    • Your storage class must be deconstructibleso it can be serialized when it’s used on a field in a migration. As longas your field has arguments that are themselves, you can use thedjango.utils.deconstruct.deconstructible class decorator for this(that’s what Django uses on FileSystemStorage).

    By default, the following methods raise NotImplementedError and willtypically have to be overridden:

    By way of example, if listing the contents of certain storage backends turnsout to be expensive, you might decide not to implement Storage.listdir.

    Ultimately, which of these methods are implemented is up to you. Leaving somemethods unimplemented will result in a partial (possibly broken) interface.

    You’ll also usually want to use hooks specifically designed for custom storageobjects. These are:

    • Required.

    Called by , this is the actual mechanism the storage classuses to open the file. This must return a File object, though in most cases,you’ll want to return some subclass here that implements logic specific to thebackend storage system.

    • save(_name, content)
    • Called by Storage.save(). The name will already have gone throughget_valid_name() and get_available_name(), and the content will be aFile object itself.
    • getvalid_name(_name)
    • Returns a filename suitable for use with the underlying storage system. Thename argument passed to this method is either the original filename sent tothe server or, if is a callable, the filename returned by thatmethod after any path information is removed. Override this to customize hownon-standard characters are converted to safe filenames.

    The code provided on Storage retains only alpha-numeric characters, periodsand underscores from the original filename, removing everything else.

    • getalternative_name(_file_root, file_ext)
    • New in Django 3.0:

    Returns an alternative filename based on the file_root and file_extparameters. By default, an underscore plus a random 7 character alphanumericstring is appended to the filename before the extension.

    • getavailable_name(_name, max_length=None)

    The length of the filename will not exceed max_length, if provided. If afree unique filename cannot be found, a exception is raised.