Static Files - potatoscript/django GitHub Wiki
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!
Letβs walk through it step by step, like building a LEGO set π§±
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
]
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
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">
π 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>
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'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.