The staticfiles app

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

参见

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

Settings

See staticfiles settings for details on thefollowing settings:

Management Commands

django.contrib.staticfiles exposes three management commands.

collectstatic

  • django-admin collectstatic
  • Collects the static files into STATIC_ROOT.

Duplicate file names are by default resolved in a similar way to how templateresolution works: the file that is first found in one of the specifiedlocations will be used. If you're confused, the findstatic commandcan help show you which files are found.

On subsequent collectstatic runs (if STATIC_ROOT isn't empty), filesare copied only if they have a modified timestamp greater than the timestamp ofthe file in STATIC_ROOT. Therefore if you remove an application fromINSTALLED_APPS, it's a good idea to use the collectstatic
—clear
option in order to remove stale static files.

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

The collectstatic management command calls thepost_process()method of the STATICFILES_STORAGE after each run and passesa list of paths that have been found by the management command. It alsoreceives all command line options of collectstatic. This is usedby the ManifestStaticFilesStorageby default.

By default, collected files receive permissions fromFILE_UPLOAD_PERMISSIONS and collected directories receive permissionsfrom FILE_UPLOAD_DIRECTORY_PERMISSIONS. If you would like differentpermissions for these files and/or directories, you can subclass either of thestatic files storage classes and specify thefile_permissions_mode and/or directory_permissions_mode parameters,respectively. For example:

  1. from django.contrib.staticfiles import storage
  2.  
  3. class MyStaticFilesStorage(storage.StaticFilesStorage):
  4. def __init__(self, *args, **kwargs):
  5. kwargs['file_permissions_mode'] = 0o640
  6. kwargs['directory_permissions_mode'] = 0o760
  7. super().__init__(*args, **kwargs)

Then set the STATICFILES_STORAGE setting to'path.to.MyStaticFilesStorage'.

Some commonly used options are:

  • —noinput, —no-input
  • Do NOT prompt the user for input of any kind.

  • —ignore PATTERN, -i PATTERN

  • Ignore files, directories, or paths matching this glob-style pattern. Usemultiple times to ignore more. When specifying a path, always use forwardslashes, even on Windows.

Changed in Django 2.2:
Path matching was added.

  • —dry-run, -n
  • Do everything except modify the filesystem.

  • —clear, -c

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

  • —link, -l

  • Create a symbolic link to each file instead of copying.

  • —no-post-process

  • Don't call thepost_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:

  1. $ python manage.py collectstatic --help
  1. ...\> py manage.py collectstatic --help

Customizing the ignored pattern list

The default ignored pattern list, ['CVS', '.', '~'], can be customized ina more persistent way than providing the —ignore command option at eachcollectstatic invocation. Provide a custom AppConfigclass, override the ignore_patterns attribute of this class and replace'django.contrib.staticfiles' with that class path in yourINSTALLED_APPS setting:

  1. from django.contrib.staticfiles.apps import StaticFilesConfig
  2.  
  3. class MyStaticFilesConfig(StaticFilesConfig):
  4. ignore_patterns = [...] # your custom ignore list

findstatic

  • django-admin findstatic staticfile [staticfile …]
  • Searches for one or more relative paths with the enabled finders.

For example:

  1. $ python manage.py findstatic css/base.css admin/js/core.js
  2. Found 'css/base.css' here:
  3. /home/special.polls.com/core/static/css/base.css
  4. /home/polls.com/core/static/css/base.css
  5. Found 'admin/js/core.js' here:
  6. /home/polls.com/src/django/contrib/admin/media/js/core.js
  1. ...\> py manage.py findstatic css\base.css admin\js\core.js
  2. Found 'css/base.css' here:
  3. /home/special.polls.com/core/static/css/base.css
  4. /home/polls.com/core/static/css/base.css
  5. Found 'admin/js/core.js' here:
  6. /home/polls.com/src/django/contrib/admin/media/js/core.js
  • findstatic —first
  • By default, all matching locations are found. To only return the first matchfor each relative path, use the —first option:
  1. $ python manage.py findstatic css/base.css --first
  2. Found 'css/base.css' here:
  3. /home/special.polls.com/core/static/css/base.css
  1. ...\> py manage.py findstatic css\base.css --first
  2. Found 'css/base.css' here:
  3. /home/special.polls.com/core/static/css/base.css

This is a debugging aid; it'll show you exactly which static file will becollected for a given path.

By setting the —verbosity flag to 0, you can suppress the extra output andjust get the path names:

  1. $ python manage.py findstatic css/base.css --verbosity 0
  2. /home/special.polls.com/core/static/css/base.css
  3. /home/polls.com/core/static/css/base.css
  1. ...\> py manage.py findstatic css\base.css --verbosity 0
  2. /home/special.polls.com/core/static/css/base.css
  3. /home/polls.com/core/static/css/base.css

On the other hand, by setting the —verbosity flag to 2, you can get allthe directories which were searched:

  1. $ python manage.py findstatic css/base.css --verbosity 2
  2. Found 'css/base.css' here:
  3. /home/special.polls.com/core/static/css/base.css
  4. /home/polls.com/core/static/css/base.css
  5. Looking in the following locations:
  6. /home/special.polls.com/core/static
  7. /home/polls.com/core/static
  8. /some/other/path/static
  1. ...\> py manage.py findstatic css\base.css --verbosity 2
  2. Found 'css/base.css' here:
  3. /home/special.polls.com/core/static/css/base.css
  4. /home/polls.com/core/static/css/base.css
  5. Looking in the following locations:
  6. /home/special.polls.com/core/static
  7. /home/polls.com/core/static
  8. /some/other/path/static

runserver

  • django-admin runserver [addrport]
  • Overrides the core runserver command if the staticfiles appis installed and adds automatic serving of staticfiles. File serving doesn't run through MIDDLEWARE.

The command adds these options:

  • —nostatic
  • Use the —nostatic option to disable serving of static files with thestaticfiles app entirely. This option isonly available if the staticfiles app isin your project's INSTALLED_APPS setting.

Example usage:

  1. $ django-admin runserver --nostatic
  1. ...\> django-admin runserver --nostatic
  • —insecure
  • Use the —insecure option to force serving of static files with thestaticfiles app even if the DEBUGsetting is False. By using this you acknowledge the fact that it'sgrossly inefficient and probably insecure. This is only intended forlocal development, should never be used in production and is onlyavailable if the staticfiles app isin your project's INSTALLED_APPS setting.

—insecure doesn't work with ManifestStaticFilesStorage.

Example usage:

  1. $ django-admin runserver --insecure
  1. ...\> django-admin runserver --insecure

Storages

StaticFilesStorage

  • class storage.StaticFilesStorage
  • A subclass of the FileSystemStoragestorage backend that uses the STATIC_ROOT setting as the basefile system location and the STATIC_URL setting respectivelyas the base URL.

  • storage.StaticFilesStorage.postprocess(_paths, **options)

  • If this method is defined on a storage, it's called by thecollectstatic management command after each run and gets passed thelocal storages and paths of found files as a dictionary, as well as the commandline options. It yields tuples of three values:original_path, processed_path, processed. The path values are strings andprocessed is a boolean indicating whether or not the value waspost-processed, or an exception if post-processing failed.

The ManifestStaticFilesStorageuses this behind the scenes to replace the paths with their hashedcounterparts and update the cache appropriately.

ManifestStaticFilesStorage

  • class storage.ManifestStaticFilesStorage
  • A subclass of the StaticFilesStoragestorage backend which stores the file names it handles by appending the MD5hash of the file's content to the filename. For example, the filecss/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 somepages still refer to those files, e.g. because they are cached by you ora 3rd party proxy server. Additionally, it's very helpful if you want toapply far future Expires headers to the deployed files to speed up theload time for subsequent page visits.

The storage backend automatically replaces the paths found in the savedfiles matching other saved files with the path of the cached copy (usingthe post_process()method). The regular expressions used to find those paths(django.contrib.staticfiles.storage.HashedFilesMixin.patterns)by default covers the @import rule and url() statement of CascadingStyle Sheets. For example, the 'css/styles.css' file with thecontent

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

would be replaced by calling the url()method of the ManifestStaticFilesStorage storage backend, ultimatelysaving a 'css/styles.55e7cbb9ba48.css' file with the followingcontent:

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

  • storage.ManifestStaticFilesStorage.max_post_process_passes
  • Since static files might reference other static files that need to have theirpaths replaced, multiple passes of replacing paths may be needed until the filehashes converge. To prevent an infinite loop due to hashes not converging (forexample, if 'foo.css' references 'bar.css' which references'foo.css') there is a maximum number of passes before post-processing isabandoned. In cases with a large number of references, a higher number ofpasses might be needed. Increase the maximum number of passes by subclassingManifestStaticFilesStorage and setting the max_post_process_passesattribute. It defaults to 5.

To enable the ManifestStaticFilesStorage you have to make sure thefollowing requirements are met:

  • the STATICFILES_STORAGE setting is set to'django.contrib.staticfiles.storage.ManifestStaticFilesStorage'
  • the DEBUG setting is set to False
  • you've collected all your static files by using thecollectstatic management command
    Since creating the MD5 hash can be a performance burden to your websiteduring runtime, staticfiles will automatically store the mapping withhashed names for all processed files in a file called staticfiles.json.This happens once when you run the collectstatic managementcommand.

  • storage.ManifestStaticFilesStorage.manifest_strict

  • If a file isn't found in the staticfiles.json manifest at runtime, aValueError is raised. This behavior can be disabled by subclassingManifestStaticFilesStorage and setting the manifest_strict attribute toFalse — nonexistent paths will remain unchanged.

Due to the requirement of running collectstatic, this storagetypically shouldn't be used when running tests as collectstatic isn't runas part of the normal test setup. During testing, ensure that theSTATICFILES_STORAGE setting is set to something else like'django.contrib.staticfiles.storage.StaticFilesStorage' (the default).

  • storage.ManifestStaticFilesStorage.filehash(_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 asmentioned above. Feel free to override this method to use your ownhashing algorithm.

CachedStaticFilesStorage

  • class storage.CachedStaticFilesStorage

2.2 版后已移除: CachedStaticFilesStorage is deprecated as it has some intractableproblems, some of which are outlined below. UseManifestStaticFilesStorage or a third-party cloud storageinstead.

CachedStaticFilesStorage is a similar class like theManifestStaticFilesStorage classbut uses Django's caching framework for storing thehashed names of processed files instead of a static manifest file calledstaticfiles.json. This is mostly useful for situations in which you don'thave access to the file system.

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.

警告

CachedStaticFilesStorage isn't recommended — in almost all casesManifestStaticFilesStorage is a better choice. There are severalperformance penalties when using CachedStaticFilesStorage since a cachemiss requires hashing files at runtime. Remote file storage require severalround-trips to hash a file on a cache miss, as several file accesses arerequired to ensure that the file hash is correct in the case of nested filepaths.

ManifestFilesMixin

  • class storage.ManifestFilesMixin
  • Use this mixin with a custom storage to append the MD5 hash of the file'scontent to the filename as ManifestStaticFilesStorage does.

Finders Module

staticfiles finders has a searched_locations attribute which is a listof directory paths in which the finders searched. Example usage:

  1. from django.contrib.staticfiles import finders
  2.  
  3. result = finders.find('css/base.css')
  4. searched_locations = finders.searched_locations

Other Helpers

There are a few other helpers outside of thestaticfiles app to work with staticfiles:

Static file development view

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

  • views.serve(request, path)
  • This view function serves static files in development.

警告

This view will only work if DEBUG is True.

That's because this view is grossly inefficient and probablyinsecure. This is only intended for local development, and shouldnever be used in production.

注解

To guess the served files' content types, this view relies on themimetypes module from the Python standard library, which itselfrelies on the underlying platform's map files. If you find that this viewdoesn't return proper content types for certain files, it is most likelythat the platform's map files need to be updated. This can be achieved, forexample, by installing or updating the mailcap package on a Red Hatdistribution, or mime-support on a Debian distribution.

This view is automatically enabled by runserver (with aDEBUG setting set to True). To use the view with a differentlocal development server, add the following snippet to the end of yourprimary URL configuration:

  1. from django.conf import settings
  2. from django.contrib.staticfiles import views
  3. from django.urls import re_path
  4.  
  5. if settings.DEBUG:
  6. urlpatterns += [
  7. re_path(r'^static/(?P<path>.*)$', views.serve),
  8. ]

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

Since this is a bit finicky, there's also a helper function that'll do this foryou:

  • urls.staticfiles_urlpatterns()
  • This will return the proper URL pattern for serving static files to youralready defined pattern list. Use it like this:
  1. from django.contrib.staticfiles.urls import staticfiles_urlpatterns
  2.  
  3. # ... the rest of your URLconf here ...
  4.  
  5. urlpatterns += staticfiles_urlpatterns()

This will inspect your STATIC_URL setting and wire up the viewto serve static files accordingly. Don't forget to set theSTATICFILES_DIRS setting appropriately to letdjango.contrib.staticfiles know where to look for files in addition tofiles in app directories.

警告

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

That's because this view is grossly inefficient and probablyinsecure. This is only intended for local development, and shouldnever be used in production.

Specialized test case to support 'live testing'

Just like its parent, you can use it to write tests that involve running thecode under test and consuming it with testing tools through HTTP (e.g. Selenium,PhantomJS, etc.), because of which it's needed that the static assets are alsopublished.

But given the fact that it makes use of thedjango.contrib.staticfiles.views.serve() view described above, it cantransparently overlay at test execution-time the assets provided by thestaticfiles finders. This means you don't need to runcollectstatic before or as a part of your tests setup.