Mastering Django Static Files

Informal Namespacing

“If I called my app polls, then why do I put my CSS at polls/static/polls/app.css? Why do I need that second polls?”

This question, or variants thereof, comes up regularly.

So what is the point of having a second polls dir inside polls/static?

Failproof Favicons

In pretty much every Django project I’ve written, I have a URL pattern for ^favicon.ico$' in my urls.py.

I’ve seen a lot of different ways people try to handle favicons; lots of them rely on unstated assumptions, and I really don’t like those. So here’s what I do:

1
2
3
4
5
6
7
8
9
10
11
12
from django.contrib.staticfiles.storage import staticfiles_storage
from django.views.generic.base import RedirectView

urlpatterns = patterns('',
    url(
        r'^favicon.ico$',
        RedirectView.as_view(
            url=staticfiles_storage.url('favicon.ico'),
            permanent=False),
        name="favicon"
    ),
    # ...

Setting Up Static File Caching

Even a fairly light-weight page will probably load some CSS and JS, and a few images – it’s pretty easy to find each page load triggering at least a dozen subsequent fetches. Now this doesn’t mean the files will be re-fetched – a sensible webserver setup will respond with 304 (Not Modified) and no content, so the browser will use its cache, but those are requests that don’t need to be made, and only so many that your server will handle at once.

Understanding Django’s Staticfiles App

Django’s handling of static files is great, but sometimes causes confusion. If you’re wondering how it all fits together, what some of the settings mean, or just want some example uses, then keep reading.

If you want to understand the fundamentals of how the excellent staticfiles app works in Django, what the configuration options mean, and how to get them right, then look no further than this article I wrote for my personal blog: Django and Static Files.