Skip to content

Static Files

PotatoScript edited this page Apr 8, 2025 · 1 revision

🧒 What's a "Static File"?

In simple terms:

Static files are the files that don't change when your site is running.

These include:

  • 🎨 CSS → Styling (colors, fonts, layout)
  • 🧠 JavaScript → Behaviors (pop-ups, animations, buttons)
  • 🖼️ Images → Logos, icons, photos

These files are used by your HTML templates to make everything look and feel better!


🧱 Step-by-Step: Setting Up Static Files in Django

Let’s walk through it step by step, like building a LEGO set 🧱


🔧 1. Add Static Settings to settings.py

In your main project folder (the one with settings.py), add or check the following:

# settings.py

import os

STATIC_URL = '/static/'  # This is the base URL

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static')  # Global static folder
]

🗂️ 2. Create the Folder Structure

In your root folder, create:

my_project/
├── static/                   ← 🌍 Global static folder
│   ├── css/
│   │   └── style.css
│   ├── js/
│   │   └── script.js
│   └── images/
│       └── logo.png

Each app can also have its own static folder if needed:

my_app/
├── static/
│   └── my_app/
│       ├── style.css
│       └── logo.png

🧙 3. Load Static Files in Templates

At the top of your HTML, always load static like this:

{% load static %}

Then use:

<!-- CSS -->
<link rel="stylesheet" href="{% static 'css/style.css' %}">

<!-- JavaScript -->
<script src="{% static 'js/script.js' %}"></script>

<!-- Image -->
<img src="{% static 'images/logo.png' %}" alt="Logo">

If you're using app-specific files:

<link rel="stylesheet" href="{% static 'my_app/style.css' %}">
<img src="{% static 'my_app/logo.png' %}" alt="Logo">

✨ 4. Example: CSS That Colors Your Page

📄 static/css/style.css

body {
    background-color: #fff0f5;
    font-family: Comic Sans MS;
    text-align: center;
    padding: 40px;
}

h1 {
    color: #ff69b4;
    font-size: 48px;
}

p {
    font-size: 20px;
    color: #333;
}

📄 templates/my_app/home.html

{% load static %}
<!DOCTYPE html>
<html>
<head>
    <title>Pretty Home Page</title>
    <link rel="stylesheet" href="{% static 'css/style.css' %}">
</head>
<body>
    <h1>🎀 Welcome to My Cute Django Site!</h1>
    <p>This page is styled using CSS from the static folder!</p>
    <img src="{% static 'images/logo.png' %}" alt="My Logo" width="200">
</body>
</html>

🧪 5. Run the Server & See the Magic

Start your server:

python manage.py runserver

Then open your browser and go to:
http://127.0.0.1:8000

You’ll see a styled page with your image and layout! 🎉✨


🧹 When You Go to Production…

When you're ready to put your site online (hosted somewhere), you need to collect all static files into one place:

python manage.py collectstatic

This command grabs all static files from your project and apps and moves them to a central place.


Clone this wiki locally