How to Load Static Files in Django Template Correctly
To load static files in a Django template, first add
{% load static %} at the top of your template. Then use {% static 'path/to/file' %} to reference your static files like CSS, JavaScript, or images.Syntax
Use {% load static %} at the beginning of your Django template to enable static file loading. Then use {% static 'relative/path/to/file' %} inside your HTML to get the correct URL for the static file.
{% load static %}: Loads the static template tag library.{% static '...' %}: Returns the URL for the given static file path.
django
{% load static %}
<img src="{% static 'images/logo.png' %}" alt="Logo">Output
<img src="/static/images/logo.png" alt="Logo">
Example
This example shows how to load a CSS file and an image in a Django template using the static tag.
django
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Static Files Example</title>
<link rel="stylesheet" href="{% static 'css/style.css' %}">
</head>
<body>
<h1>Welcome to Django Static Example</h1>
<img src="{% static 'images/django-logo.png' %}" alt="Django Logo">
</body>
</html>Output
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Static Files Example</title>
<link rel="stylesheet" href="/static/css/style.css">
</head>
<body>
<h1>Welcome to Django Static Example</h1>
<img src="/static/images/django-logo.png" alt="Django Logo">
</body>
</html>
Common Pitfalls
Common mistakes when loading static files include:
- Forgetting to add
{% load static %}at the top of the template. - Using
STATIC_URLdirectly in templates instead of the{% static %}tag. - Not configuring
STATICFILES_DIRSorSTATIC_ROOTproperly insettings.py. - Trying to load static files without running
collectstaticin production.
Always use the {% static %} tag to ensure correct URLs.
django
{# Wrong: missing load static #}
<img src="{% static 'images/logo.png' %}">
{# Right: include load static #}
{% load static %}
<img src="{% static 'images/logo.png' %}">Quick Reference
| Step | Description | Example |
|---|---|---|
| 1 | Load static template tag library | {% load static %} |
| 2 | Use static tag to get file URL | {% static 'path/to/file' %} |
| 3 | Reference static files in HTML | ![]() |
| 4 | Configure STATICFILES_DIRS in settings.py | STATICFILES_DIRS = [BASE_DIR / 'static'] |
| 5 | Run collectstatic in production | python manage.py collectstatic |
Key Takeaways
Always start your template with {% load static %} to enable static file loading.
Use {% static 'path/to/file' %} to get the correct URL for static files in templates.
Configure static file settings properly in settings.py for development and production.
Never hardcode static URLs; always use the static template tag for portability.
Run collectstatic before deploying to production to gather all static files.
