Django Tutorial menu

Django Static Files

Static files are the files your site uses that do not change per visitor: CSS, JavaScript, fonts and images.

Static vs Media Files

TypeWho adds themExamples
Static filesYou, the developerstyle.css, app.js, logo
Media filesYour usersProfile pictures, uploaded CVs

Where to Put Static Files

Like templates, each app has its own static folder with the app name inside:

Example

text
courses/
    static/
        courses/
            css/
                style.css
            images/
                logo.png

django.contrib.staticfiles must be in INSTALLED_APPS (it is there by default), and settings.py has:

Example

python
STATIC_URL = "static/"

Using Static Files in a Template

Load the static tag at the top of the template, then use it to build the file's URL:

Example

html
{% load static %}
<!DOCTYPE html>
<html>
<head>
  <title>Workownix Courses</title>
  <link rel="stylesheet" href="{% static 'courses/css/style.css' %}">
</head>
<body>
  <img src="{% static 'courses/images/logo.png' %}" alt="Workownix logo">
  <h1>Our Courses</h1>
  <script src="{% static 'courses/js/app.js' %}"></script>
</body>
</html>

The page source in the browser shows:

Output
<link rel="stylesheet" href="/static/courses/css/style.css">
<img src="/static/courses/images/logo.png" alt="Workownix logo">

And a simple stylesheet, courses/static/courses/css/style.css:

Example

css
body {
  font-family: Arial, sans-serif;
  background: #f5f7f6;
}
h1 {
  color: #0c4b33;
}

If your CSS change does not appear, press Ctrl+F5 to reload without the browser cache, and check that {% load static %} is at the top of the template.

Project-wide Static Files

For files shared by all apps, create a static folder next to manage.py and tell Django about it:

Example

python
from pathlib import Path

BASE_DIR = Path(__file__).resolve().parent.parent

STATICFILES_DIRS = [BASE_DIR / "static"]

Going Live: collectstatic

During development, runserver serves static files for you (while DEBUG = True). On a live server, Django does not. You collect all static files into one folder, and the web server sends them:

Example

python
STATIC_ROOT = BASE_DIR / "staticfiles"

Example

bash
python manage.py collectstatic
Output
128 static files copied to '/home/user/mysite/staticfiles'.

Many hosts use a package called WhiteNoise to serve these files directly from Django in a simple way.

Media Files (User Uploads)

Set where uploads are saved and their URL:

Example

python
MEDIA_URL = "media/"
MEDIA_ROOT = BASE_DIR / "media"

Add a file field to a model:

Example

python
class Student(models.Model):
    name = models.CharField(max_length=100)
    photo = models.ImageField(upload_to="students/", blank=True)

ImageField needs the Pillow package: pip install pillow. During development, serve uploads by adding this to mysite/urls.py:

Example

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

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

In a template, show the photo with {{ student.photo.url }}. A form that uploads files needs enctype="multipart/form-data", and the view must pass request.FILES to the form.

Settings Summary

SettingMeaning
STATIC_URLURL prefix for static files
STATICFILES_DIRSExtra folders to look for static files
STATIC_ROOTWhere collectstatic copies files for production
MEDIA_URLURL prefix for uploads
MEDIA_ROOTFolder where uploads are saved

Exercise

Exercise

What must you write at the top of a template before using {% static %}?

Learn Django with a teacher

Join the Full Stack Development course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp