Episode 12 of 32

Static Files & Images

Serve static files like CSS, JavaScript, and images — configure Django static file handling for development and use them in templates.

Static Files & Images

Static files are CSS, JavaScript, and images that do not change per request. Django has a built-in system for serving them during development.

Creating the Static Folder

djangoblog/
├── static/
│   └── style.css
├── templates/
├── articles/
└── manage.py

Configuring Static Files

# djangoblog/settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static'),
]

Using Static Files in Templates

<!-- Load the static tag at the top -->
{% load static %}

<html>
<head>
    <link rel="stylesheet" href="{% static 'style.css' %}">
</head>
<body>
    <img src="{% static 'logo.png' %}" alt="Logo">
    <script src="{% static 'app.js' %}"> </script>
</body>
</html>

The {% static %} tag generates the correct URL for static files. Always use it instead of hardcoding paths.

A Basic Stylesheet

/* static/style.css */
body {
    font-family: Arial, sans-serif;
    max-width: 960px;
    margin: 0 auto;
    padding: 20px;
}

.article {
    border-bottom: 1px solid #eee;
    padding: 20px 0;
}

nav {
    background: #333;
    padding: 15px;
}

nav a {
    color: white;
    margin-right: 15px;
    text-decoration: none;
}

Key Takeaways

  • Static files go in a static/ directory at the project root
  • Configure STATICFILES_DIRS in settings.py
  • Use {% load static %} and {% static 'file' %} in templates
  • Never hardcode static file paths — always use the template tag