[Answered ]-How to dynamically select storage option for models.FileField?

2👍

For what you’re trying to do you may be better off making a custom storage backend and just overriding the various bits of S3BotoStorage.
In particular if you make bucket_name a property you should be able to get the behavior you want.

EDIT:

To expand a bit on that, the source for S3BotoStorage.__init__ has the bucket as an optional argument. Additionally bucket when it’s used in the class is a @param, making it easy to override. The following code is untested, but should be enough to give you a starting point

class MyS3BotoStorage(S3BotoStorage):
    @property
    def bucket(self):
        if self._filename.endswith('.jpg'):
            return self._get_or_create_bucket('SomeBucketName')
        else:
            return self._get_or_create_bucket('SomeSaneDefaultBucket')

    def _save(self, name, content):
        # This part might need some work to normalize the name and all...
        self._filename = name
        return super(MyS3BotoStorage, self)._save(name, content)
👤Paul

Leave a comment