Static files are assets that do not change dynamically, such as CSS files, JavaScript files, images, fonts, and icons. Django provides a built-in system for managing and serving these files during development and deployment.
Why Use Static Files?
- Add styling with CSS
- Add interactivity with JavaScript
- Display images and icons
- Organize frontend assets efficiently
- Improve website appearance and user experience
Static Files Directory Structure
A common project structure looks like this:
project/
│
├── app/
├── static/
│ ├── css/
│ │ └── style.css
│ ├── js/
│ │ └── script.js
│ └── images/
│ └── logo.png
│
├── templates/
├── manage.py
└── settings.py
Configure Static Files
Add the following settings in settings.py:
STATIC_URL = 'static/'
For a custom static directory:
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent.parent
STATIC_URL = '/static/'
STATICFILES_DIRS = [
BASE_DIR / "static",
]
Load Static Files in Templates
Before using static files, load the static template tag:
{% load static %}
Add CSS File
{% load static %}
<link rel="stylesheet" href="{% static 'css/style.css' %}">
Add JavaScript File
{% load static %}
<script src="{% static 'js/script.js' %}"></script>
Display an Image
{% load static %}
<img src="{% static 'images/logo.png' %}" alt="Logo">
Example Template
{% load static %}
<!DOCTYPE html>
<html>
<head>
<title>Django Static Files</title>
<link rel="stylesheet" href="{% static 'css/style.css' %}">
</head>
<body>
<img src="{% static 'images/logo.png' %}" alt="Logo">
<script src="{% static 'js/script.js' %}"></script>
</body>
</html>
Collect Static Files for Production
When deploying a Django project, collect all static files into a single directory:
python manage.py collectstatic
Configure in settings.py:
STATIC_ROOT = BASE_DIR / "staticfiles"
Benefits of Static Files
- Better organization of frontend assets
- Easy management of CSS, JavaScript, and images
- Improved website performance
- Simplified deployment process
- Reusable assets across applications