← Back to Chapters

Handling Static Files (CSS, JS, Images)

?️ Handling Static Files (CSS, JS, Images)

? Quick Overview

Static files such as CSS, JavaScript, and images enhance the appearance and functionality of Django applications. Django provides a structured and reliable way to manage these assets during development and production.

? Key Concepts

  • Static files are non-dynamic assets
  • Managed using Django settings
  • Served automatically in development
  • Collected for production use

? Syntax / Theory

Django uses STATIC_URL, STATICFILES_DIRS, and STATIC_ROOT to locate and serve static files. The collectstatic command gathers all assets for deployment.

? Code Examples

? View Code Example
# Static file base URL
STATIC_URL = '/static/'

# Additional static directories
STATICFILES_DIRS = [
    BASE_DIR / "static",
]
? View Code Example
# Load static template tag
{% load static %}

<link rel="stylesheet" href="{% static 'css/styles.css' %}">
<script src="{% static 'js/script.js' %}"></script>
<img src="{% static 'images/logo.png' %}" alt="Logo">
? View Code Example
# Typical static folder structure
static/
├── css/
│   └── styles.css
├── js/
│   └── script.js
└── images/
    └── logo.png
? View Code Example
# Enable staticfiles app
INSTALLED_APPS = [
    'django.contrib.staticfiles',
]
? View Code Example
# Collect static files for production
python manage.py collectstatic

? Live Output / Explanation

  • Static files load correctly in templates
  • Django resolves URLs automatically
  • Production servers serve collected files efficiently

? Interactive Example: Static URL Resolver

Click a file in the directory structure to see how Django's {% static %} tag would resolve the path based on a STATIC_URL = '/static/' setting.

? Project Structure
my_project/
? static/
? css/base.css
? js/main.js
? img/logo.png
? Template Resolution

Template Tag:

{% static '...' %}

Rendered HTML Path:

Select a file...

? Use Cases

  • Styling pages with CSS
  • Adding interactivity using JavaScript
  • Displaying logos and images

✅ Tips & Best Practices

  • Always organize static files into folders
  • Use the {% static %} tag
  • Run collectstatic before deployment

? Try It Yourself

  • Create a static directory structure
  • Link assets in a template
  • Run and test collectstatic