Static Files in Django
Static files are CSS stylesheets, JavaScript files, images, and other assets that don't change dynamically. Django provides a robust system for managing these files across development and production environments.
The key difference between development and production is that development serves files directly from your app's directories, while production uses collectstatic to gather everything into a single location for your web server.
Configuring Static Files
Start by adding these settings to your project's settings.py. STATIC_URL defines the URL prefix for static files. STATICFILES_DIRS tells Django where to find additional static files beyond each app's static folder.
STATIC_URL = '/static/'
STATIC_ROOT = BASE_DIR / 'staticfiles'
STATICFILES_DIRS = [
BASE_DIR / 'static',
]
STATIC_ROOT is where collectstatic copies all static files for production. STATICFILES_DIRS lets you keep project-wide static files in a separate directory.
Loading Static Files in Templates
To use static files in templates, load the static template library first. Then use the {% static %} tag to generate URLs for your files.
{% load static %}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="{% static 'css/style.css' %}">
<script src="{% static 'js/main.js' %}"></script>
</head>
<body>
<img src="{% static 'images/logo.png' %}" alt="Logo">
</body>
</html>
The {% static %} tag generates the full URL path. This way, you don't have to hardcode /static/ in your templates.
Organizing Static Files Per App
The best practice is to keep each app's static files inside a static directory named after the app. This makes it easy to find and manage files as your project grows.
myapp/
static/
myapp/
css/
style.css
js/
app.js
images/
logo.png
templates/
...
The double nesting (static/myapp/) prevents naming conflicts between apps. When you reference files, include the app name in the path.
{% load static %}
<link rel="stylesheet" href="{% static 'myapp/css/style.css' %}">
Collecting Static Files for Production
When you deploy to production, run collectstatic to gather all static files from your apps and STATICFILES_DIRS into STATIC_ROOT. Your web server then serves files from this single directory.
python manage.py collectstatic
This command copies everything into the STATIC_ROOT directory. Run it every time you deploy new static files. In production, your web server (Nginx, Apache) serves files from this directory instead of Django handling it directly.