From 210657b791fec359a9109b69e566018253edfad0 Mon Sep 17 00:00:00 2001 From: miigotu Date: Tue, 31 Mar 2020 12:12:39 +0200 Subject: Fixed #28184 -- Allowed using a callable for FileField and ImageField storage. --- docs/ref/models/fields.txt | 9 +++++++-- docs/releases/3.1.txt | 5 +++++ docs/topics/files.txt | 28 ++++++++++++++++++++++++++++ 3 files changed, 40 insertions(+), 2 deletions(-) (limited to 'docs') diff --git a/docs/ref/models/fields.txt b/docs/ref/models/fields.txt index 7c5401046b..7ca0b96d85 100644 --- a/docs/ref/models/fields.txt +++ b/docs/ref/models/fields.txt @@ -822,8 +822,13 @@ Has two optional arguments: .. attribute:: FileField.storage - A storage object, which handles the storage and retrieval of your - files. See :doc:`/topics/files` for details on how to provide this object. + A storage object, or a callable which returns a storage object. This + handles the storage and retrieval of your files. See :doc:`/topics/files` + for details on how to provide this object. + + .. versionchanged:: 3.1 + + The ability to provide a callable was added. The default form widget for this field is a :class:`~django.forms.ClearableFileInput`. diff --git a/docs/releases/3.1.txt b/docs/releases/3.1.txt index fd1bd4f40c..7df81329b4 100644 --- a/docs/releases/3.1.txt +++ b/docs/releases/3.1.txt @@ -248,6 +248,11 @@ File Storage * ``FileSystemStorage.save()`` method now supports :class:`pathlib.Path`. +* :class:`~django.db.models.FileField` and + :class:`~django.db.models.ImageField` now accept a callable for ``storage``. + This allows you to modify the used storage at runtime, selecting different + storages for different environments, for example. + File Uploads ~~~~~~~~~~~~ diff --git a/docs/topics/files.txt b/docs/topics/files.txt index dbe9549818..73d0a11fff 100644 --- a/docs/topics/files.txt +++ b/docs/topics/files.txt @@ -202,3 +202,31 @@ For example, the following code will store uploaded files under :doc:`Custom storage systems ` work the same way: you can pass them in as the ``storage`` argument to a :class:`~django.db.models.FileField`. + +Using a callable +---------------- + +.. versionadded:: 3.1 + +You can use a callable as the :attr:`~django.db.models.FileField.storage` +parameter for :class:`~django.db.models.FileField` or +:class:`~django.db.models.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 :class:`~django.core.files.storage.Storage`. + +For example:: + + from django.conf import settings + from django.db import models + from .storages import MyLocalStorage, MyRemoteStorage + + + def select_storage(): + return MyLocalStorage() if settings.DEBUG else MyRemoteStorage() + + + class MyModel(models.Model): + my_file = models.FileField(storage=select_storage) -- cgit v1.3