Django Static Files


Details

Static files are non-changing resources such as images, CSS stylesheets, JavaScript files, fonts, and icons. These help shape how your site looks and behaves on the front end.


What Are Static Files?

Unlike templates or views, static items don’t process logic. They stay the same for every user. Common examples:

  • style.css – controls colors, layout, fonts
  • script.js – adds interactivity
  • logo.png – displays a picture or brand image

Organize Your Static Content

Inside your app folder (e.g., members/), make a new directory called static, and within it, a subfolder named after your app:

members/ 
└── static/     
        └── members/         
                 ├── style.css         
                 └── image.png

This naming pattern helps Django track where each file belongs.


Configure Global Settings

Open your project’s settings.py and make sure this setting exists:

STATIC_URL = '/static/'

This tells Django where to serve static resources from during development.


Load Static Assets in Templates

Inside your HTML layout, first enable static access at the top:

{% load static %}

Then use static tags to insert files:

<link rel="stylesheet" href="{% static 'members/style.css' %}">
<img src="{% static 'members/image.png' %}" alt="Photo"> 

This way, Django finds and inserts the correct path to your static resources.


Example HTML with Static Usage

Here’s a quick example:

{% load static %} 
<!DOCTYPE html> 
<html> 
<head>   
    <link rel="stylesheet" href="{% static 'members/style.css' %}"> 
</head> 
<body>   
    <h1>Welcome!</h1>   
    <img src="{% static 'members/image.png' %}" alt="Sample Image"> 
</body> 
</html>

Collecting for Deployment (Advanced)

When moving your project to a live environment, use:

python manage.py collectstatic

This command gathers all static items into a single place, usually for production hosting.


Summary

  • Static files are fixed assets like stylesheets, scripts, and graphics
  • Keep them in static/yourapp/
  • Use {% load static %} to activate them in templates
  • Insert them with {% static 'path/to/file' %}
  • For deployment, collectstatic prepares everything in one location

Prefer Learning by Watching?

Watch these YouTube tutorials to understand HTML Tutorial visually:

What You'll Learn:
  • 📌 Django Tutorial #12 - Static Files & Images
  • 📌 #11 Django tutorials | Static Files - 2
Previous Next