Movatterモバイル変換


[0]ホーム

URL:


Skip to main content
Django

The web framework for perfectionists with deadlines.

Documentation

  • Language:en

How to manage static files (e.g. images, JavaScript, CSS)

Websites generally need to serve additional files such as images, JavaScript,or CSS. In Django, we refer to these files as “static files”. Django providesdjango.contrib.staticfiles to help you manage them.

This page describes how you can serve these static files.

Configuring static files

  1. Make sure thatdjango.contrib.staticfiles is included in yourINSTALLED_APPS.

  2. In your settings file, defineSTATIC_URL, for example:

    STATIC_URL="static/"
  3. In your templates, use thestatic template tag to build the URL forthe given relative path using the configuredstaticfilesSTORAGES alias.

    {%loadstatic%}<imgsrc="{%static'my_app/example.jpg'%}"alt="My image">
  4. Store your static files in a folder calledstatic in your app. Forexamplemy_app/static/my_app/example.jpg.

Serving the files

In addition to these configuration steps, you’ll also need to actuallyserve the static files.

During development, if you usedjango.contrib.staticfiles, this willbe done automatically byrunserver whenDEBUG is settoTrue (seedjango.contrib.staticfiles.views.serve()).

This method isgrossly inefficient and probablyinsecure,so it isunsuitable for production.

SeeHow to deploy static files for proper strategies to servestatic files in production environments.

Your project will probably also have static assets that aren’t tied to aparticular app. In addition to using astatic/ directory inside your apps,you can define a list of directories (STATICFILES_DIRS) in yoursettings file where Django will also look for static files. For example:

STATICFILES_DIRS=[BASE_DIR/"static","/var/www/static/",]

See the documentation for theSTATICFILES_FINDERS setting fordetails on howstaticfiles finds your files.

Static file namespacing

Now wemight be able to get away with putting our static files directlyinmy_app/static/ (rather than creating anothermy_appsubdirectory), but it would actually be a bad idea. Django will use thefirst static file it finds whose name matches, and if you had a static filewith the same name in adifferent application, Django would be unable todistinguish between them. We need to be able to point Django at the rightone, and the best way to ensure this is bynamespacing them. That is,by putting those static files insideanother directory named for theapplication itself.

You can namespace static assets inSTATICFILES_DIRS byspecifyingprefixes.

Serving static files during development

If you usedjango.contrib.staticfiles as explained above,runserver will do this automatically whenDEBUG is settoTrue. If you don’t havedjango.contrib.staticfiles inINSTALLED_APPS, you can still manually serve static files using thedjango.views.static.serve() view.

This is not suitable for production use! For some common deploymentstrategies, seeHow to deploy static files.

For example, if yourSTATIC_URL is defined asstatic/, you cando this by adding the following snippet to yoururls.py:

fromdjango.confimportsettingsfromdjango.conf.urls.staticimportstaticurlpatterns=[# ... 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 ifthe given prefix is local (e.g.static/) and not a URL (e.g.http://static.example.com/).

Also this helper function only serves the actualSTATIC_ROOTfolder; it doesn’t perform static files discovery likedjango.contrib.staticfiles.

Finally, static files are served via a wrapper at the WSGI applicationlayer. As a consequence, static files requests do not pass through thenormalmiddleware chain.

Serving files uploaded by a user during development

During development, you can serve user-uploaded media files fromMEDIA_ROOT using thedjango.views.static.serve() view.

This is not suitable for production use! For some common deploymentstrategies, seeHow to deploy static files.

For example, if yourMEDIA_URL is defined asmedia/, you can dothis by adding the following snippet to yourROOT_URLCONF:

fromdjango.confimportsettingsfromdjango.conf.urls.staticimportstaticurlpatterns=[# ... 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 ifthe 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-intesting client (i.e. when using the built-inLiveServerTestCase) the static assets need to be served alongthe rest of the content so the test environment reproduces the real one asfaithfully as possible, butLiveServerTestCase has only very basic staticfile-serving functionality: It doesn’t know about the finders feature of thestaticfiles application and assumes the static content has already beencollected underSTATIC_ROOT.

Because of this,staticfiles ships its owndjango.contrib.staticfiles.testing.StaticLiveServerTestCase, asubclass of the built-in one that has the ability to transparently serve allthe assets during execution of these tests in a way very similar to what we getat development time withDEBUG=True, i.e. without having to collect themusingcollectstatic first.

Deployment

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

  1. Set theSTATIC_ROOT setting to the directory from which you’dlike to serve these files, for example:

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

    $pythonmanage.pycollectstatic

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

  3. Use a web server of your choice to serve thefiles.How to deploy static files covers some common deploymentstrategies for static files.

Learn more

This document has covered the basics and some common usage patterns. Forcomplete details on all the settings, commands, template tags, and other piecesincluded indjango.contrib.staticfiles, seethe staticfilesreference.

Back to Top

Additional Information

Support Django!

Support Django!

Contents

Getting help

FAQ
Try the FAQ — it's got answers to many common questions.
Index,Module Index, orTable of Contents
Handy when looking for specific information.
Django Discord Server
Join the Django Discord Community.
Official Django Forum
Join the community on the Django Forum.
Ticket tracker
Report bugs with Django or Django documentation in our ticket tracker.

Download:

Offline (development version):HTML |PDF |ePub
Provided byRead the Docs.

Diamond and Platinum Members

Sentry
JetBrains
This document is for Django's development version, which can be significantly different from previous releases. For older releases, use the version selector floating in the bottom right corner of this page.

[8]ページ先頭

©2009-2025 Movatter.jp