Unable to use custom StaticFilesStorage

24 views
Skip to first unread message

Stodge

unread,
Nov 1, 2017, 6:35:08 PM11/1/17
to Django users
I'm trying to add an extra directory for each app that will contain Javascript/CSS files. I created a custom storage.py in my app containing a copy of the code from Django's AppDirectoriesFinder class, but I changed source_dir from "static" to "catalog". I'll include the Django code with the modified source_dir so no-one has to check the source code:

class AppCatalogStorage(FileSystemStorage):
   
"""
    A file system storage backend that takes an app module and works
    for the ``catalog`` directory of it.
    """

    prefix
= None
    source_dir
= 'catalog'  <------- changed, was 'static'


   
def __init__(self, app, *args, **kwargs):
       
"""
        Returns a static file storage if available in the given app.
        """

       
# app is the actual app module
        mod
= import_module(app)
        mod_path
= os.path.dirname(upath(mod.__file__))
        location
= os.path.join(mod_path, self.source_dir)
       
super(AppCatalogStorage, self).__init__(location, *args, **kwargs)



I added this to my settings file:

    STATICFILES_STORAGE = (

       
'myapp.storage.AppCatalogStorage',
       
'django.contrib.staticfiles.storage.StaticFilesStorage'
   
)


My understanding here is that I can then do:

(Assuming my app name is fred)

fred/catalog/js/someJavascript.js
fred
/catalog/css/someStylesheet.css


I also assumed they would then be accessible as:

/static/fred/js/someJavascript.js
/static/fred/css/someStylesheet.css


However, neither file is available at the expected URL. Did I misunderstand something?

Thanks

Stodge

unread,
Nov 1, 2017, 7:49:13 PM11/1/17
to Django users
As usual, despite working on this for a while, the solution hits me after I post here.

I have to define a custom finder that uses my custom storage. Bingo!

class CatalogFinder(AppDirectoriesFinder):

    storage_class
= AppCatalogStorage

   
def __init__(self, apps=None, *args, **kwargs):
       
super(CatalogFinder, self).__init__(*args, **kwargs)


STATICFILES_FINDERS = (
   
"django.contrib.staticfiles.finders.FileSystemFinder",
   
"django.contrib.staticfiles.finders.AppDirectoriesFinder",
   
"myapp.finders.CatalogFinder"
)

Stodge

unread,
Nov 2, 2017, 1:45:23 PM11/2/17
to Django users
There's a flaw in my plan as STATICFILES_STORAGE is a string and not a tuple. 

James Schneider

unread,
Nov 3, 2017, 4:34:33 PM11/3/17
to django...@googlegroups.com
Quite honestly, instead of doing all of this work, why not just amend STATICFILES_DIRS with the location of your extra folder? Or just use the designated 'static/app_name' location for your JS files? Seems like a ton of trouble now and in the future to try and implement your own file structure. A symlink from catalog -> static/fred would also have the same effect if you are on a Linux system. 

-James
 


Reply all
Reply to author
Forward
0 new messages