The staticfiles app

django.contrib.staticfiles collects static files from each of your applications (and any other places you specify) into a single location that can easily be served in production.

See also

For an introduction to the static files app and some usage examples, see Managing static files (CSS, images). For guidelines on deploying static files, see Deploying static files.

Settings

Note

The following settings control the behavior of the staticfiles app.

STATICFILES_DIRS

Default: []

This setting defines the additional locations the staticfiles app will traverse if the FileSystemFinder finder is enabled, e.g. if you use the collectstatic or findstatic management command or use the static file serving view.

This should be set to a list or tuple of strings that contain full paths to your additional files directory(ies) e.g.:

STATICFILES_DIRS = (
    "/home/special.polls.com/polls/static",
    "/home/polls.com/polls/static",
    "/opt/webfiles/common",
)

Prefixes (optional)

In case you want to refer to files in one of the locations with an additional namespace, you can optionally provide a prefix as (prefix, path) tuples, e.g.:

STATICFILES_DIRS = (
    # ...
    ("downloads", "/opt/webfiles/stats"),
)

Example:

Assuming you have STATIC_URL set '/static/', the collectstatic management command would collect the “stats” files in a 'downloads' subdirectory of STATIC_ROOT.

This would allow you to refer to the local file '/opt/webfiles/stats/polls_20101022.tar.gz' with '/static/downloads/polls_20101022.tar.gz' in your templates, e.g.:

<a href="{{ STATIC_URL }}downloads/polls_20101022.tar.gz">

STATICFILES_STORAGE

Default: 'django.contrib.staticfiles.storage.StaticFilesStorage'

The file storage engine to use when collecting static files with the collectstatic management command.

A ready-to-use instance of the storage backend defined in this setting can be found at django.contrib.staticfiles.storage.staticfiles_storage.

For an example, see Serving static files from a cloud service or CDN.

STATICFILES_FINDERS

Default:

("django.contrib.staticfiles.finders.FileSystemFinder",
 "django.contrib.staticfiles.finders.AppDirectoriesFinder")

The list of finder backends that know how to find static files in various locations.

The default will find files stored in the STATICFILES_DIRS setting (using django.contrib.staticfiles.finders.FileSystemFinder) and in a static subdirectory of each app (using django.contrib.staticfiles.finders.AppDirectoriesFinder). If multiple files with the same name are present, the first file that is found will be used.

One finder is disabled by default: django.contrib.staticfiles.finders.DefaultStorageFinder. If added to your STATICFILES_FINDERS setting, it will look for static files in the default file storage as defined by the DEFAULT_FILE_STORAGE setting.

Note

When using the AppDirectoriesFinder finder, make sure your apps can be found by staticfiles. Simply add the app to the INSTALLED_APPS setting of your site.

Static file finders are currently considered a private interface, and this interface is thus undocumented.

Management Commands

django.contrib.staticfiles exposes three management commands.

collectstatic

django-admin.py collectstatic

Collects the static files into STATIC_ROOT.

Duplicate file names are by default resolved in a similar way to how template resolution works: the file that is first found in one of the specified locations will be used. If you’re confused, the findstatic command can help show you which files are found.

Files are searched by using the enabled finders. The default is to look in all locations defined in STATICFILES_DIRS and in the 'static' directory of apps specified by the INSTALLED_APPS setting.

The collectstatic management command calls the post_process() method of the STATICFILES_STORAGE after each run and passes a list of paths that have been found by the management command. It also receives all command line options of collectstatic. This is used by the CachedStaticFilesStorage by default.

Some commonly used options are:

--noinput

Do NOT prompt the user for input of any kind.

-i <pattern>
--ignore <pattern>

Ignore files or directories matching this glob-style pattern. Use multiple times to ignore more.

-n
--dry-run

Do everything except modify the filesystem.

-c
--clear

Clear the existing files before trying to copy or link the original file.

-l

Create a symbolic link to each file instead of copying.

--no-post-process

Don’t call the post_process() method of the configured STATICFILES_STORAGE storage backend.

--no-default-ignore

Don’t ignore the common private glob-style patterns 'CVS', '.*' and '*~'.

For a full list of options, refer to the commands own help by running:

$ python manage.py collectstatic --help

findstatic

django-admin.py findstatic

Searches for one or more relative paths with the enabled finders.

For example:

$ python manage.py findstatic css/base.css admin/js/core.js
/home/special.polls.com/core/static/css/base.css
/home/polls.com/core/static/css/base.css
/home/polls.com/src/django/contrib/admin/media/js/core.js

By default, all matching locations are found. To only return the first match for each relative path, use the --first option:

$ python manage.py findstatic css/base.css --first
/home/special.polls.com/core/static/css/base.css

This is a debugging aid; it’ll show you exactly which static file will be collected for a given path.

runserver

django-admin.py runserver

Overrides the core runserver command if the staticfiles app is installed and adds automatic serving of static files and the following new options.

--nostatic

Use the --nostatic option to disable serving of static files with the staticfiles app entirely. This option is only available if the staticfiles app is in your project’s INSTALLED_APPS setting.

Example usage:

django-admin.py runserver --nostatic
--insecure

Use the --insecure option to force serving of static files with the staticfiles app even if the DEBUG setting is False. By using this you acknowledge the fact that it’s grossly inefficient and probably insecure. This is only intended for local development, should never be used in production and is only available if the staticfiles app is in your project’s INSTALLED_APPS setting. runserver --insecure doesn’t work with CachedStaticFilesStorage.

Example usage:

django-admin.py runserver --insecure

Storages

StaticFilesStorage

class storage.StaticFilesStorage

A subclass of the FileSystemStorage storage backend that uses the STATIC_ROOT setting as the base file system location and the STATIC_URL setting respectively as the base URL.

post_process(paths, **options)

This method is called by the collectstatic management command after each run and gets passed the local storages and paths of found files as a dictionary, as well as the command line options.

The CachedStaticFilesStorage uses this behind the scenes to replace the paths with their hashed counterparts and update the cache appropriately.

CachedStaticFilesStorage

class storage.CachedStaticFilesStorage

A subclass of the StaticFilesStorage storage backend which caches the files it saves by appending the MD5 hash of the file’s content to the filename. For example, the file css/styles.css would also be saved as css/styles.55e7cbb9ba48.css.

The purpose of this storage is to keep serving the old files in case some pages still refer to those files, e.g. because they are cached by you or a 3rd party proxy server. Additionally, it’s very helpful if you want to apply far future Expires headers to the deployed files to speed up the load time for subsequent page visits.

The storage backend automatically replaces the paths found in the saved files matching other saved files with the path of the cached copy (using the post_process() method). The regular expressions used to find those paths (django.contrib.staticfiles.storage.CachedStaticFilesStorage.cached_patterns) by default cover the @import rule and url() statement of Cascading Style Sheets. For example, the 'css/styles.css' file with the content

@import url("../admin/css/base.css");

would be replaced by calling the url() method of the CachedStaticFilesStorage storage backend, ultimatively saving a 'css/styles.55e7cbb9ba48.css' file with the following content:

@import url("../admin/css/base.27e20196a850.css");

To enable the CachedStaticFilesStorage you have to make sure the following requirements are met:

  • the STATICFILES_STORAGE setting is set to 'django.contrib.staticfiles.storage.CachedStaticFilesStorage'
  • the DEBUG setting is set to False
  • you use the staticfiles static template tag to refer to your static files in your templates
  • you’ve collected all your static files by using the collectstatic management command

Since creating the MD5 hash can be a performance burden to your website during runtime, staticfiles will automatically try to cache the hashed name for each file path using Django’s caching framework. If you want to override certain options of the cache backend the storage uses, simply specify a custom entry in the CACHES setting named 'staticfiles'. It falls back to using the 'default' cache backend.

file_hash(name, content=None)

The method that is used when creating the hashed name of a file. Needs to return a hash for the given file name and content. By default it calculates a MD5 hash from the content’s chunks as mentioned above.

Template tags

static

Uses the configured STATICFILES_STORAGE storage to create the full URL for the given relative path, e.g.:

{% load static from staticfiles %}
<img src="{% static "images/hi.jpg" %}" alt="Hi!" />

The previous example is equal to calling the url method of an instance of STATICFILES_STORAGE with "images/hi.jpg". This is especially useful when using a non-local storage backend to deploy files as documented in Serving static files from a cloud service or CDN.

If you’d like to retrieve a static URL without displaying it, you can use a slightly different call:

{% load static from staticfiles %}
{% static "images/hi.jpg" as myphoto %}
<img src="{{ myphoto }}" alt="Hi!" />

Other Helpers

There are a few other helpers outside of the staticfiles app to work with static files:

Static file development view

The static files tools are mostly designed to help with getting static files successfully deployed into production. This usually means a separate, dedicated static file server, which is a lot of overhead to mess with when developing locally. Thus, the staticfiles app ships with a quick and dirty helper view that you can use to serve files locally in development.

views.serve(request, path)

This view function serves static files in development.

Warning

This view will only work if DEBUG is True.

That’s because this view is grossly inefficient and probably insecure. This is only intended for local development, and should never be used in production.

This view is automatically enabled by runserver (with a DEBUG setting set to True). To use the view with a different local development server, add the following snippet to the end of your primary URL configuration:

from django.conf import settings

if settings.DEBUG:
    urlpatterns += patterns('django.contrib.staticfiles.views',
        url(r'^static/(?P<path>.*)$', 'serve'),
    )

Note, the beginning of the pattern (r'^static/') should be your STATIC_URL setting.

Since this is a bit finicky, there’s also a helper function that’ll do this for you:

urls.staticfiles_urlpatterns()

This will return the proper URL pattern for serving static files to your already defined pattern list. Use it like this:

from django.contrib.staticfiles.urls import staticfiles_urlpatterns

# ... the rest of your URLconf here ...

urlpatterns += staticfiles_urlpatterns()

This will inspect your STATIC_URL setting and wire up the view to serve static files accordingly. Don’t forget to set the STATICFILES_DIRS setting appropriately to let django.contrib.staticfiles know where to look for files in addition to files in app directories.

Warning

This helper function will only work if DEBUG is True and your STATIC_URL setting is neither empty nor a full URL such as http://static.example.com/.

That’s because this view is grossly inefficient and probably insecure. This is only intended for local development, and should never be used in production.