Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 77 ยท Templates

Static Files and Media

Learn how Django handles static files and uploads, from STATIC_URL and collectstatic to MEDIA_ROOT, FileField, the storage API and serving files in development.

Every real website needs more than HTML: stylesheets, JavaScript, logos, and often files that your users upload, such as avatars or PDF invoices. Django splits these into two clearly separated kinds of files, and understanding the split saves you from most deployment surprises.

  • Static files are part of your project. You wrote them (or a library did), they change only when you deploy, and every visitor sees the same copy: CSS, JavaScript, fonts, icons.
  • Media files are created while the site runs. Users upload them, and they differ from user to user.

Django does not serve either kind in production. A web server such as nginx, or a CDN, does that far faster. What Django provides is the bookkeeping: settings that say where files live, a template tag that builds URLs, a command that gathers everything in one folder, and a storage API that hides where uploads end up.

Static versus media at a glance

flowchart LR
    subgraph Dev["Your project"]
        A["app/static/<br/>site.css"]
        B["assets/<br/>app.js"]
    end
    A --> C["collectstatic"]
    B --> C
    C --> D["STATIC_ROOT<br/>(deployed folder)"]
    D --> W["Web server / CDN<br/>at STATIC_URL"]
    U["User upload"] --> M["MEDIA_ROOT<br/>(or cloud storage)"]
    M --> W2["Web server<br/>at MEDIA_URL"]

Static files are gathered at deploy time; media files arrive at run time and live in their own place.

The runnable examples below create real folders in a scratch directory (the in-browser Python has a temporary file system that disappears when the page closes), so you can watch the same commands that run on your own machine. All examples on this page start with the same settings.configure(...) block. The browser keeps one Django per page and settings can only be configured once, so whichever example you run first sets them for the others.

The static settings

Four settings control static files:

Setting Meaning
STATIC_URL URL prefix for static files, such as "/static/". Must end with a slash.
STATICFILES_DIRS Extra folders to search, besides each app's own static/ folder.
STATIC_ROOT Single folder that collectstatic fills for production. Never put your own files here.
STORAGES["staticfiles"] The storage class used to write and name collected files.

To find files, Django asks a list of finders. By default the first looks in every folder listed in STATICFILES_DIRS, the second in the static/ folder of every installed app. This is how a reusable app can ship its own CSS (the admin does exactly that). To avoid name clashes between apps, the usual convention is to nest files in a folder named after the app: blog/static/blog/blog.css, referenced as blog/blog.css.

You need django.contrib.staticfiles in INSTALLED_APPS. Then templates use the static tag, never a hard-coded path:

Python The static tag and the finders

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice what the tag does: it prefixes STATIC_URL. Because your templates never contain /static/ literally, you can move all assets to a CDN by changing one setting, as the last line shows. The as logo form stores the URL in a variable, just like the simple tags in Custom Template Tags and Filters.

Also note that finders.find() returned a result for a file that exists and None for one that does not. The finder does not check the name you typed in a template, which is why a typo in {% static 'css/sitee.css' %} silently produces a broken link. Django only complains about missing files when a manifest storage is in use, which leads to the next section.

collectstatic and hashed file names

During development, the runserver command (with DEBUG = True) serves static files straight from the finders. In production there is no such magic. Instead you run:

Terminal
python manage.py collectstatic

This copies every file found by every finder into STATIC_ROOT, as one tidy tree that nginx or a CDN can serve. Because users and CDNs cache static files aggressively, new deployments need new URLs, or visitors keep the stale CSS. The ManifestStaticFilesStorage class solves this: it copies each file under a name that includes a hash of its content, and writes a staticfiles.json manifest that maps the original name to the hashed one. The static tag reads the manifest, so your templates keep using the plain name.

Python collectstatic with hashed names

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Each source file appears twice: once under its original name and once with a hash (site.4490f3af9829.css). Change one character of site.css and the hash, and therefore the URL, changes, so browsers fetch the new file at once while unchanged files stay cached forever. The staticfiles.json file is the manifest the tag consults.

In production, deploy with DEBUG = False, run collectstatic as part of your build, and make the web server serve STATIC_ROOT at STATIC_URL. A popular shortcut for small sites is the WhiteNoise package, which lets Django's own process serve the collected folder efficiently. The deployment lesson covers this in detail.

Media: uploaded files

User uploads work through a different pair of settings:

Python
# settings.py
MEDIA_ROOT = BASE_DIR / "media"   # where uploaded files are written
MEDIA_URL = "/media/"             # URL prefix that points to them

Never set MEDIA_ROOT equal to STATIC_ROOT, and never let uploads end up inside your source tree where collectstatic or your editor might trip over them.

On a model, the FileField (and its subclass ImageField, which needs the Pillow package) stores the path of the file in a database column and the bytes in a storage backend. The upload_to argument decides the folder and name below MEDIA_ROOT: either a string such as "avatars/%Y/%m/" (with date placeholders) or a function.

All file access goes through the storage API, an object with a small, consistent interface: save(), open(), exists(), size(), url(), delete(). The default is FileSystemStorage, which writes to MEDIA_ROOT. Swapping to Amazon S3 or another cloud store (with a package such as django-storages) changes the backend, and your model and view code stays the same. The next example uses InMemoryStorage, a built-in backend that keeps bytes in memory, so you can see every method work without touching disk.

Python The storage API and a FileField

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Study the output carefully:

  • save() returns the name actually used. When the name is taken, the storage appends a short random suffix instead of overwriting. Always store the returned name, never the one you asked for. (The suffix is random, so the example only checks its shape.)
  • The model column holds just the relative path documents/ada/budget.txt. The storage turns it into a URL with doc.file.url, and in a template you simply write {{ doc.file.url }}.
  • SimpleUploadedFile is the class Django's test tools use to fake an upload. In a real request the same data arrives as request.FILES, which you will meet in Query Strings, Forms and Request Data.

Security notes for uploads

Uploaded files are untrusted input. Django already strips directory components from file names, but you should still do the following:

  1. Limit size and type. Check file.size and the extension (and, for images, let ImageField verify it is a real image). Do not trust the content_type the browser claims.
  2. Never serve uploads from the same origin as executable content if you accept arbitrary file types. A user who uploads an HTML file could otherwise run script in your site's context.
  3. Keep media out of the code path. The web server should serve uploads as plain data, never execute them.

Serving media and static files in development

With runserver and DEBUG = True, static files work automatically, but media files do not. During development you add a URL pattern that uses Django's static helper:

Python
# urls.py
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    # ... your routes ...
]

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

This helper adds a route that calls django.views.static.serve, and it returns an empty list when DEBUG is off, so it is harmless in production. The view is deliberately slow and not hardened, which is why Django documents it as a development aid only. The example below calls the same view directly to show how it behaves, including its protection against paths that try to escape the folder:

Python The development serve view

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The existing file comes back with status 200, a missing one with 404, and a path with .. is refused outright (status 400). Real deployments never rely on this view; they let nginx or object storage deliver files, usually with caching headers and often through a CDN.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which statement correctly separates static files from media files?

    Static files (CSS, JavaScript, images you bundle) belong to the project and change at deploy time. Media files are generated while the site runs, for example uploaded avatars.
  2. 2. What does python manage.py collectstatic do?

    collectstatic gathers static files from every app's static folder and from STATICFILES_DIRS into the single STATIC_ROOT folder, which the web server then serves.
  3. 3. Why is ManifestStaticFilesStorage useful?

    The hash in the file name changes whenever the content does. Browsers and CDNs can cache each URL forever, and a deploy with new content automatically uses fresh URLs.
  4. 4. A FileField column in the database contains which of these?

    The column holds the name relative to the storage. The bytes live in the storage backend, and file.url builds the public URL from MEDIA_URL (or the cloud backend's rules).

Summary

  • Static files belong to the project; media files are created at run time. Keep their settings (STATIC_* and MEDIA_*) separate.
  • Use {% load static %} and {% static 'path' %} in templates, so a single setting controls where assets are served from.
  • collectstatic gathers all static files into STATIC_ROOT; ManifestStaticFilesStorage adds content hashes for safe long-term caching.
  • FileField stores a path in the database and delegates the bytes to a storage backend with save, open, exists, size, url and delete.
  • Treat uploads as untrusted. Serve static and media files from a web server or CDN in production, and use the static() URL helper only during development.

Now that pages can be rendered and styled, it is time to give them data. Start with Models and Fields.