Beginner-Friendly Topic
Take your time - it's perfectly normal to re-read this topic 2-3 times. Try the interactive code editor below to run code yourself. Use the Q&A section to check your understanding before moving on. You've got this! 🚀
Static Files Setup (CSS, JS, Images)
Static files are CSS, JavaScript, images, and fonts that don't change per request. Django has a built-in staticfiles app that collects and serves static files. Proper setup is essential for both development and production.
Static Files Setup
- STATIC_URL = '/static/' - URL prefix for static files
- STATICFILES_DIRS = [BASE_DIR / 'static'] - Project-wide static dirs
- STATIC_ROOT = BASE_DIR / 'staticfiles' - Production collection dir
- {% load static %} - Load the static template tag
- {% static 'css/style.css' %} - Generate URL for static file
- python manage.py collectstatic - Collect for production
- Each app can have its own static/ directory
Static Files Example
# settings.py
# STATIC_URL = '/static/'
# STATICFILES_DIRS = [BASE_DIR / 'static']
# STATIC_ROOT = BASE_DIR / 'staticfiles'
# Directory structure:
# mysite/
# static/
# css/style.css
# js/main.js
# images/logo.png
# blog/
# static/blog/
# css/blog.css
# In templates - load and use static files
# {% load static %}
# <!DOCTYPE html>
# <html>
# <head>
# <link rel="stylesheet" href="{% static 'css/style.css' %}">
# </head>
# <body>
# <img src="{% static 'images/logo.png' %}" alt="Logo">
# <script src="{% static 'js/main.js' %}"></script>
# </body>
# </html>
# Production: collect all static files
# python manage.py collectstatic?? Tip
Tip
Put shared CSS/JS in the project-level static/ folder. App-specific assets go in each app's static/appname/ folder.
QuerySets are LAZY - no DB hit until evaluated.
?? Common Mistake
Warning
Referencing static files with hardcoded paths like /static/style.css. Use {% static 'style.css' %} which works across environments.
?? Practice Task
Note
(1) Add a CSS file to static/. (2) Link it with {% static %}. (3) Add an image and verify it loads correctly.
Quick Quiz
Key Takeaways
- Static files are CSS, JavaScript, images, and fonts that don't change per request.
- STATIC_URL = '/static/' - URL prefix for static files
- STATICFILES_DIRS = [BASE_DIR / 'static'] - Project-wide static dirs
- STATIC_ROOT = BASE_DIR / 'staticfiles' - Production collection dir