diff options
| author | Ahmed Nassar <a.moh.nassar00@gmail.com> | 2025-04-06 08:45:28 +0200 |
|---|---|---|
| committer | Sarah Boyce <42296566+sarahboyce@users.noreply.github.com> | 2025-04-15 10:10:33 +0200 |
| commit | cbdb1bed041a88a5e29cab5e60da928b2d9e6db5 (patch) | |
| tree | 96dedb86a9c1049bbd25b7cddf91798926540d5f /docs/topics | |
| parent | aa2c7659d5d95fde3072903b7bd70d16f7d6e045 (diff) | |
[5.2.x] Fixed #36269 -- Documented how to test callable storage in FileField.
Backport of 8bca33f68acc4fc881146c4b9cf4101a8bfab437 from main.
Diffstat (limited to 'docs/topics')
| -rw-r--r-- | docs/topics/files.txt | 33 |
1 files changed, 33 insertions, 0 deletions
diff --git a/docs/topics/files.txt b/docs/topics/files.txt index 0a983b6cd3..0c4d1e5c6c 100644 --- a/docs/topics/files.txt +++ b/docs/topics/files.txt @@ -272,3 +272,36 @@ use :data:`~django.core.files.storage.storages`:: class MyModel(models.Model): upload = models.FileField(storage=select_storage) + +Because the callable is evaluated when your models classes are loaded, if you +need to override the :setting:`STORAGES` setting in tests, you should use a +``LazyObject`` subclass instead:: + + from django.core.files.storage import storages + from django.utils.functional import LazyObject + + + class OtherStorage(LazyObject): + def _setup(self): + self._wrapped = storages["mystorage"] + + + my_storage = OtherStorage() + + + class MyModel(models.Model): + upload = models.FileField(storage=my_storage) + +The ``LazyObject`` delays the evaluation of the storage until it's actually +needed, allowing :func:`~django.test.override_settings` to take effect:: + + @override_settings( + STORAGES={ + "mystorage": { + "BACKEND": "django.core.files.storage.InMemoryStorage", + } + } + ) + def test_storage(): + model = MyModel() + assert isinstance(model.upload.storage, InMemoryStorage) |
