Managing static files (e.g. images, JavaScript, CSS)

网站通常需要提供其他文件,如图片,JavaScript或CSS。 在Django中,我们将这些文件称为“静态文件”。 Django提供了django.contrib.staticfiles来帮助你管理它们。

本页介绍如何提供这些静态文件。

Configuring static files

  1. 确保django.contrib.staticfiles包含在INSTALLED_APPS中。

  2. 在您的设置文件中,定义STATIC_URL,例如:

    STATIC_URL = '/static/'
    
  3. 在你的模板中,要么像/static/my_app/example.jpg一样硬编码url,或者最好使用static模板标记来构建给定相对路径的URL使用已配置的STATICFILES_STORAGE存储(当您要切换到提供静态文件的内容传送网络(CDN)时,这会更容易)。

    {% load static %}
    <img src="{% static "my_app/example.jpg" %}" alt="My image"/>
    
  4. 将您的静态文件存储在您的应用中名为static的文件夹中。 例如my_app/static/my_app/example.jpg

Serving the files

除了这些配置步骤之外,您还需要实际提供静态文件。

在开发过程中,如果使用django.contrib.staticfiles,当DEBUG设置为True时,runserver会自动完成这些(请参阅django.contrib.staticfiles.views.serve())。

这种方法非常低效,可能不安全,所以不适合生产

有关正确的策略,请参阅部署静态文件以在生产环境中提供静态文件。

您的项目可能还会有不与特定应用绑定的静态资产。 除了在应用程序中使用static/目录之外,您还可以在设置文件中定义一个目录列表(STATICFILES_DIRS),Django将在其中查找静态文件。 For example:

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),
    '/var/www/static/',
]

See the documentation for the STATICFILES_FINDERS setting for details on how staticfiles finds your files.

Static file namespacing

Now we might be able to get away with putting our static files directly in my_app/static/ (rather than creating another my_app subdirectory), but it would actually be a bad idea. Django will use the first static file it finds whose name matches, and if you had a static file with the same name in a different application, Django would be unable to distinguish between them. We need to be able to point Django at the right one, and the easiest way to ensure this is by namespacing them. That is, by putting those static files inside another directory named for the application itself.

Serving static files during development

如果您使用django.contrib.staticfiles,则runserver会在DEBUG设置为True时自动执行。 If you don’t have django.contrib.staticfiles in INSTALLED_APPS, you can still manually serve static files using the django.views.static.serve() view.

This is not suitable for production use! For some common deployment strategies, see Deploying static files.

For example, if your STATIC_URL is defined as /static/, you can do this by adding the following snippet to your urls.py:

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    # ... the rest of your URLconf goes here ...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

Note

This helper function works only in debug mode and only if the given prefix is local (e.g. /static/) and not a URL (e.g. http://static.example.com/).

Also this helper function only serves the actual STATIC_ROOT folder; it doesn’t perform static files discovery like django.contrib.staticfiles.

Serving files uploaded by a user during development

During development, you can serve user-uploaded media files from MEDIA_ROOT using the django.views.static.serve() view.

This is not suitable for production use! For some common deployment strategies, see Deploying static files.

For example, if your MEDIA_URL is defined as /media/, you can do this by adding the following snippet to your urls.py:

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    # ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Note

This helper function works only in debug mode and only if the given prefix is local (e.g. /media/) and not a URL (e.g. http://media.example.com/).

Testing

When running tests that use actual HTTP requests instead of the built-in testing client (i.e. when using the built-in LiveServerTestCase) the static assets need to be served along the rest of the content so the test environment reproduces the real one as faithfully as possible, but LiveServerTestCase has only very basic static file-serving functionality: It doesn’t know about the finders feature of the staticfiles application and assumes the static content has already been collected under STATIC_ROOT.

Because of this, staticfiles ships its own django.contrib.staticfiles.testing.StaticLiveServerTestCase, a subclass of the built-in one that has the ability to transparently serve all the assets during execution of these tests in a way very similar to what we get at development time with DEBUG = True, i.e. without having to collect them using collectstatic first.

Deployment

django.contrib.staticfiles provides a convenience management command for gathering static files in a single directory so you can serve them easily.

  1. Set the STATIC_ROOT setting to the directory from which you’d like to serve these files, for example:

    STATIC_ROOT = "/var/www/example.com/static/"
    
  2. Run the collectstatic management command:

    $ python manage.py collectstatic
    

    This will copy all files from your static folders into the STATIC_ROOT directory.

  3. Use a web server of your choice to serve the files. Deploying static files covers some common deployment strategies for static files.

Learn more

This document has covered the basics and some common usage patterns. For complete details on all the settings, commands, template tags, and other pieces included in django.contrib.staticfiles, see the staticfiles reference.