0
0
DjangoHow-ToBeginner · 3 min read

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_URL directly in templates instead of the {% static %} tag.
  • Not configuring STATICFILES_DIRS or STATIC_ROOT properly in settings.py.
  • Trying to load static files without running collectstatic in 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

StepDescriptionExample
1Load static template tag library{% load static %}
2Use static tag to get file URL{% static 'path/to/file' %}
3Reference static files in HTML
4Configure STATICFILES_DIRS in settings.pySTATICFILES_DIRS = [BASE_DIR / 'static']
5Run collectstatic in productionpython 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.