Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django CachedStaticFilesStorage in ModelAdmin Media

I'm using the CachedStaticFilesStorage backend in Django 1.7 and having a problem with static files in the admin interface.

In the ModelAdmin class, you can define a Media class with static files to add to the add/change views. To apply the hash to these files, I'm using the static function in django.contrib.staticfiles.templatetags.staticfiles. E.g.:

from django.contrib.staticfiles.templatetags.staticfiles import static

class MyAdminClass(admin.ModelAdmin):

    class Media:
        js = [
            static('app/static_file.js'),
            static('app/static_file_2.js'),
        ]

This appeared to be working, because the static files had already been collected before this change had been made. But, when I remove the static files and attempt to run collectstatic it fails with the error:

ValueError: The file 'app/static_file.js' could not be found with <django.contrib.staticfiles.storage.CachedStaticFilesStorage object at 0x80910a9d0>

In fact, you can't run any django command, as it tries to load the admin app and it fails when it gets to the point of trying to run the static command on the static file that hasn't been collected yet.

Does anyone have any ideas of a way around this?

like image 905
user1543967 Avatar asked Feb 06 '15 12:02

user1543967


People also ask

What is {% load static %} in Django?

The {% static %} template tag generates the absolute URL of static files. That's all you need to do for development. Reload http://localhost:8000/polls/ and you should see that the question links are green (Django style!) which means that your stylesheet was properly loaded.

What does Django Collectstatic do?

Django also provides a mechanism for collecting static files into one place so that they can be served easily. Using the collectstatic command, Django looks for all static files in your apps and collects them wherever you told it to, i.e. the STATIC_ROOT .


1 Answers

I found a solution to this, in case anyone else comes across this issue. You can set a media property on the ModelAdmin class to return the Media class and defer the loading of the media.

from django.forms import Media

@property
def media(self):
    js = [
        'app/static_files.js',
        'app/static_files_2.js',
    ]

    return Media(js=[static(path) for path in js])
like image 91
user1543967 Avatar answered Nov 08 '22 02:11

user1543967