Django中的自定义默认文件存储 [英] Custom default file storage in Django
问题描述
我正在尝试使用自定义文件存储(https://bitbucket.org/david/django-storages/wiki/S3Storage)。我按照指示,将其放在我的settings.py
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'
当我去导入default_storage时,它不是S3BotoStorage的类型。我必须调用_setup()。但是当我这样做,我的模型的领域仍然是DefaultStorage类型
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>
>>>
我的模型的字段如何是S3BotoStorage类型?
How can my model's field be of the S3BotoStorage type?
推荐答案
根据我对django存储的了解,存储类始终是DefaultStorage(除非您在模型中明确设置)。它在_wrapped类应该看。
您尝试打印p.original.storage._wrapped吗?
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" ?
从我身边,我得到的结果与您一样,但如果我打印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())
在这种情况下,您可以执行 p.file.storage
,您将获得您的自定义类而不是DefaultStorage包装。
In that case, you can do p.file.storage
and you will get your custom class instead of the DefaultStorage wrapper.
这篇关于Django中的自定义默认文件存储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!