Django not able to find static files[Solved]
Django Static Files Not Working - Fix Guide
In this article, you will learn how to fix the problem of Django not loading static files. This is the easiest and safest solution for Django 3.1 and above.
Introduction
In Django 3.1 and above, the settings.py file uses pathlib.Path instead of os.path to handle directory structures. This means static file configurations using os.path.join won't work unless you import os at the top of your settings file.
Note: This article is for DEBUG = True. For DEBUG = False, follow: Static files not working when DEBUG = False
Step-by-Step Solution
Step 1: Define BASE_DIR
Ensure BASE_DIR is defined in settings.py. If not, add it:
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
Step 2: Check Debug Mode
Ensure debug mode is enabled in settings.py:
DEBUG = True
ALLOWED_HOSTS = []
Step 3: Configure Static Files
Define STATIC_URL and STATICFILES_DIRS in settings:
Note: For Django 3.1+, you need to import os and use it for static paths.
STATIC_URL = '/static/' # the path in url
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
Step 4: Use Static Template Tag
In templates, use the static template tag to build URLs for static files. Store files in my_app/static/image/example.jpg:
{% load static %}
Welcome! to coderwebsite
My Django project
- • Create a static folder at your project root directory
- • Use
{% load static %}at the top of your templates - • Reference static files using
{% static 'path/to/file' %}
Step 5: Run Django Server
Start the development server:
python manage.py runserver
Success! Static files will now load correctly in your Django project!
Recommended Directory Structure
my_django_project/
├── manage.py
├── my_app/
│ └── static/
│ ├── css/
│ │ └── styles.css
│ ├── js/
│ │ └── script.js
│ └── images/
│ └── logo.png
├── static/ (project-level static files)
│ └── ...
└── settings.py
Key Points
Import os
Always import os when using os.path.join in Django 3.1+
Load Static
Use {% load static %} in every template that uses static files
DEBUG True
Static files are auto-served in development when DEBUG = True
Collectstatic
In production, run python manage.py collectstatic
Common Mistakes to Avoid
- Missing os import: Forgetting to import
osin Django 3.1+ - Incorrect path: Using wrong BASE_DIR or static directory path
- Wrong template syntax: Using
{static}instead of{% static %} - Hardcoded paths: Using hardcoded
/static/instead of template tag
Summary
Fixing Django static files requires proper configuration in settings.py and correct template syntax. The key is ensuring os is imported and STATICFILES_DIRS is properly set up.
Remember to use the {% load static %} template tag and reference static files using the {% static %} tag for proper URL generation.