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.
Django uses STATIC_URL, STATICFILES_DIRS, and STATIC_ROOT to locate and serve static files. The collectstatic command gathers all assets for deployment.
# Static file base URL
STATIC_URL = '/static/'
# Additional static directories
STATICFILES_DIRS = [
BASE_DIR / "static",
]
# 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">
# Typical static folder structure
static/
├── css/
│ └── styles.css
├── js/
│ └── script.js
└── images/
└── logo.png
# Enable staticfiles app
INSTALLED_APPS = [
'django.contrib.staticfiles',
]
# Collect static files for production
python manage.py collectstatic
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.
Template Tag:
{% static '...' %}
Rendered HTML Path:
Select a file...{% static %} tagcollectstatic before deployment