[Django]-Django โ€“ how to reference paths of static files and can I use them in models?

2๐Ÿ‘

โœ…

I would like to throw in another one:
Using STATIC_ROOT will break if you host your files externally.

You can use the django-storage-backend yourself (untested, just written):

from django.core.files.storage import get_storage_class
from django.conf import settings

def getImages(self)
    static_storage = get_storage_class(settings.STATICFILES_STORAGE)()
    directories, files = static_storage.listdir('images')
    return [
        static_storage.url('images/' + file) 
        for file in files 
        if file.startswith(self.name) and file.endswith('.jpg')
    ]

This will even return the correct URL if you use CachedStaticFileStorage or S3BotoStorage (from django-storages). And this will also be fine if you are in dev-mode.

๐Ÿ‘คDenis Cornehl

3๐Ÿ‘

  • There is a STATIC_ROOT variable in settings.py. Why not use it?
  • Personally, I follow your way โ€“ just concatenating paths. But just found a function for that:

    from django.contrib.staticfiles.templatetags.staticfiles import static
    print static('yourfile.jpg')
    

It works for me.

  • I think model is a good place for it. You store files in filesystem like you store model data in database. In other words, both of these are examples of storage which is a model level thing.

Leave a comment