Make STATIC_URL context variable aware of backing storage with staticfiles

50 views
Skip to first unread message

Daniel R

unread,
Mar 19, 2016, 2:01:28 PM3/19/16
to Django developers (Contributions to Django itself)
I've always used the STATIC_URL context processor variable in templates and didn't have trouble with it up until a few days ago when a customer required to use the STATICFILES_STORAGE.

I then realized I would need to change all the {{STATIC_URL}} template references to use a {% static %} tag via {% load static from staticfiles %}, which just seemed overwhelming, so I just tweaked django.template.context_processors.static to make it staticfiles aware.  

Given the prevelance of templates that use {{STATIC_URL}} and now the possibility of changing storage, I thought I'd suggest this as a possible new fix/feature. Here's another post which addreses the same problem http://staticfiles.productiondjango.com/blog/stop-using-static-url-in-templates/ but simply says to use {% load static from staticfiles %} and never use {{STATIC_URL}}. But given the wide use of {{STATIC_URL}} this may be an easy and worthwhile fix instead of asking users to change template references.

What do you think ? 

Current django.template.context_processors.static is pretty basic:

def static(request):
   
"""
    Adds static-related context variables to the context.
    """

   
return {'STATIC_URL': settings.STATIC_URL}



It would change to something like 

def static(request):
   
"""
    Adds static-related context variables to the context.
    """

   
if 'django.contrib.staticfiles' in settings.INSTALLED_APPS:
       
from django.contrib.staticfiles.storage import staticfiles_storage
       
return {'STATIC_URL':staticfiles_storage.url }
   
else:
       
return {'STATIC_URL': settings.STATIC_URL}



Florian Apolloner

unread,
Mar 19, 2016, 2:34:12 PM3/19/16
to Django developers (Contributions to Django itself)


On Saturday, March 19, 2016 at 7:01:28 PM UTC+1, Daniel R wrote:
But given the wide use of {{STATIC_URL}} this may be an easy and worthwhile fix instead of asking users to change template references.

Wide? Not sure what your definition of wide is, but I suspect that the tag has way higher usage, especially since it is the only way if you want to work it with the storage backends.
 
What do you think ? 

Nothing, cause it is not as simple as you suggest, storage backends in general also change the name of the file to include a hash of the contents etc… Your only sensible option is to switch to the tag. Fwiw, writing a simple script which performs replacement in every template should be simple enough…

Cheers,
Florian
Reply all
Reply to author
Forward
0 new messages