Opened 8 years ago

Closed 8 years ago

Last modified 8 years ago

#23506 closed Uncategorized (wontfix)

How to reference static files outside of the template

Reported by: thenewguy Owned by: nobody
Component: contrib.staticfiles Version: 1.7
Severity: Normal Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no


There should be a function like django.contrib.staticfiles.templatetags.staticfiles.static that is safe to use outside of a template. When it cannot find a static file, it should probably be configured to return a url pointing at a view that logs the file is missing and returns a 404.

I just discovered that I took down an environment with one call to static from django.contrib.staticfiles.templatetags.staticfiles.

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

class FooForm(ModelForm):
    class Media:
        js = (

foo.js didn't get put in place.

So what is the correct way to reference a static file outside of a template keeping something like in mind?

Change History (4)

comment:1 Changed 8 years ago by thenewguy

Something simple like this even:

from django.contrib.staticfiles.templatetags.staticfiles import static as _static
import logging

logger = logging.getLogger(__name__)

def static(path):
        return _static(path)
        logger.exception('Exception raised looking for static file "%s"' % path)
        return u"/missing-file/%s" % path.lstrip("/")

comment:2 Changed 8 years ago by Aymeric Augustin

Resolution: wontfix
Status: newclosed

Such a function doesn't belong to Django. We aren't going to use a bare except and rely on logging instead of raising exceptions.

Referencing a static file that doesn't exist is a bug. The proper behavior is to raise an exception in that case. Silencing errors isn't "safe" or "correct".

That said, your last question points out that there's no documented way to accessing the URL of static files. For the sake of clarity, I've filed #23563 specifically about that problem.

comment:3 Changed 8 years ago by thenewguy


I understand a bare except clause would not be the final result.

But is it really best for a missing static file in a form to bring down an entire site?

Maybe the exception could be delayed until the form is rendered for missing static files. I can understand raising an exception on the page that uses it but preventing the entire application from loading seems a little extreme.

Sorry for any typos. Typed on my cell phone.


comment:4 Changed 8 years ago by Aymeric Augustin

That's entirely up to you. Have your code call static() at run time, not at compile time.

Note: See TracTickets for help on using tickets.
Back to Top