Search code examples
pythondjangoamazon-s3django-storage

How can I use django-storages for both media and static files?


I'm attempting to use http://django-storages.readthedocs.org/en/latest/backends/amazon-S3.html for serving both static files and uploaded media, but I'm not certain it's possible. Is there a documented way that I'm missing? Also, I would assume (hope) that you could configure a separate bucket for each, but I can't find any info on that.


Solution

  • Yes this is possible by configuring both DEFAULT_FILE_STORAGE and STATICFILES_STORAGE to use the S3 storage. However if you set

    DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage'
    STATICFILES_STORAGE = 'storages.backends.s3boto.S3BotoStorage'
    

    then these will both use the default settings for the S3 storage, meaning they will both use the AWS_STORAGE_BUCKET_NAME bucket. The way to work around this is to create a small subclass of S3BotoStorage in your project which uses a different setting for the bucket name.

    from django.conf import settings
    
    from storages.backends.s3boto import S3BotoStorage
    
    class S3StaticStorage(S3BotoStorage):
    
        def __init__(self, *args, **kwargs):
            kwargs['bucket']  = settings.AWS_STATIC_BUCKET_NAME
            super(S3StaticStorage, self).__init__(*args, **kwargs)
    

    You would then define the AWS_STATIC_BUCKET_NAME setting to be whatever you want for your static bucket and change AWS_STATIC_BUCKET_NAME to the path for this custom storage class.

    STATICFILES_STORAGE = 'dotted.path.to.storage.S3StaticStorage'
    

    If you wanted to change other settings such as AWS_QUERYSTRING_AUTH, AWS_S3_CUSTOM_DOMAIN, AWS_PRELOAD_METADATA, etc then you would change them in this subclass as well.