Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom default file storage in Django

Tags:

python

django

I'm trying to use a custom file storage (https://bitbucket.org/david/django-storages/wiki/S3Storage). I followed the directions and put this in my settings.py

DEFAULT_FILE_STORAGE='storages.backends.s3boto.S3BotoStorage'

When I go to import default_storage, it's not of the type S3BotoStorage. I have to make the call to _setup(). But when I do that, my model's field is still of the DefaultStorage type

Python 2.6.6 (r266:84292, Dec 29 2010, 22:02:51) 
[GCC 4.2.1 (Apple Inc. build 5646) (dot 1)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from django.core.files.storage import default_storage
>>> print default_storage
<django.core.files.storage.DefaultStorage object at 0x1016f7c10>
>>> print default_storage._wrapped
None
>>> from base.models import Payload
>>> p = Payload()
>>> p.original.storage
<django.core.files.storage.DefaultStorage object at 0x1016f7c10>
>>> default_storage._setup()
>>> print default_storage._wrapped
<storages.backends.s3boto.S3BotoStorage object at 0x101ddd8d0>
>>> p.original.storage
<django.core.files.storage.DefaultStorage object at 0x1016f7c10>
>>>

How can my model's field be of the S3BotoStorage type?

like image 317
CoolGravatar Avatar asked Feb 24 '11 17:02

CoolGravatar


1 Answers

From what I understand of django storages, the storage class will always be DefaultStorage (unless you set it explicitly in the model). It's at the _wrapped class that should look. Did you try to print "p.original.storage._wrapped" ?

From my side, I get the same results as you, but if I print p.original.storage._wrapped, I get my custom storage class ( in my case).

If you want to be sure that the correct storage is applied to your field, you can also set the storage directly in the model. For example :

from l3i.shortcuts.storage import UniqueFileStorage
class TestModel(models.Model):
    file = models.FileField(upload_to='file', storage=UniqueFileStorage())

In that case, you can do p.file.storage and you will get your custom class instead of the DefaultStorage wrapper.

like image 101
jphoude Avatar answered Oct 28 '22 23:10

jphoude