Static Files - potatoscript/django GitHub Wiki

πŸ§’ 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.


⚠️ **GitHub.com Fallback** ⚠️