简体   繁体   English

Django中的自定义默认文件存储

[英]Custom default file storage in Django

I'm trying to use a custom file storage (https://bitbucket.org/david/django-storages/wiki/S3Storage). 我正在尝试使用自定义文件存储(https://bitbucket.org/david/django-storages/wiki/S3Storage)。 I followed the directions and put this in my settings.py 我按照指示把它放在我的settings.py中

DEFAULT_FILE_STORAGE='storages.backends.s3boto.S3BotoStorage'

When I go to import default_storage, it's not of the type S3BotoStorage. 当我去导入default_storage时,它不是S3BotoStorage类型。 I have to make the call to _setup(). 我必须调用_setup()。 But when I do that, my model's field is still of the DefaultStorage type 但是当我这样做时,我的模型的字段仍然是DefaultStorage类型

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? 我的模型字段如何属于S3BotoStorage类型?

From what I understand of django storages, the storage class will always be DefaultStorage (unless you set it explicitly in the model). 根据我对django存储的理解,存储类将始终为DefaultStorage(除非您在模型中明确设置它)。 It's at the _wrapped class that should look. 它应该在_wrapped类看起来。 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). 在我这边,我得到了与你相同的结果,但如果我打印p.original.storage._wrapped,我得到我的自定义存储类(在我的情况下)。

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. 在这种情况下,您可以执行p.file.storage ,您将获得自定义类而不是DefaultStorage包装器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM