How to Fix Django Static Files Not Loading
In this tutorial, you'll learn about How to Fix Django Static Files Not Loading. We cover key concepts, practical examples, and best practices.
Django returns 404 for static files like CSS, JavaScript, and images when the static file configuration is incorrect or files have not been collected.
The Wrong Way
# settings.py
STATIC_URL = '/static/'
# STATIC_ROOT and STATICFILES_DIRS are missing
<!-- template.html -->
<link rel="stylesheet" href="/static/css/style.css">
This returns:
GET /static/css/style.css 404 Not Found
The Right Way
Configure all three static file settings:
# settings.py
STATIC_URL = '/static/'
STATIC_ROOT = BASE_DIR / 'staticfiles'
STATICFILES_DIRS = [BASE_DIR / 'static']
python manage.py collectstatic
Step-by-Step Fix
1. Verify settings.py configuration
import os
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent.parent
STATIC_URL = '/static/'
STATIC_ROOT = BASE_DIR / 'staticfiles'
STATICFILES_DIRS = [BASE_DIR / 'static']
2. Run collectstatic
python manage.py collectstatic
3. Check file locations
Ensure the static file exists in the right directory:
myproject/
static/
css/
style.css
4. Use static template tag
{% load static %}
<link rel="stylesheet" href="{% static 'css/style.css' %}">
5. Configure for development server
# urls.py
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# your URLs
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Prevention Tips
- Set
STATIC_URL,STATIC_ROOT, andSTATICFILES_DIRSin every project. - Use the
{% static %}template tag, not hardcoded paths. - Run
collectstaticbefore every deployment. - Use
python manage.py findstatic css/style.cssto locate files. - Add static file serving to urls.py during development.
Common Mistakes with django static
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists - Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
- Using
returnto exit a function early instead of wrapping a pure value in the monad
These mistakes appear frequently in real-world PYTHON code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro