Introduction to Static Files in Django
What are Static Files?
Static files are pieces of content that are not generated dynamically by the server but are served directly to the client. These include JavaScript files, CSS files, images, fonts, and other assets that are used to enhance the user interface of a web application.
Configuring Static Files in Django
To handle static files in Django, you need to define a few settings in your settings.py
file.
First, ensure you have the following settings:
STATIC_URL = '/static/'
The STATIC_URL
setting defines the base URL for serving static files.
Next, add a directory to store your static files:
STATICFILES_DIRS = [os.path.join(BASE_DIR, "static"),]
This setting tells Django where to look for static files in addition to each app's static
directory.
Creating and Using Static Files
Let's create a simple CSS file and use it in a Django template.
Step 1: Create a Static Directory
First, create a directory named static
in your Django project root. Inside this directory, create a subdirectory named css
and add a file named style.css
.
project_root/
├── static/
│ ├── css/
│ │ └── style.css
└── ...
Step 2: Add Some CSS
Open style.css
and add some basic styling:
body {
background-color: #e0f7fa;
}
h1 {
color: #007BFF;
}
Step 3: Link the CSS in a Template
Open one of your Django templates (e.g., index.html
) and load the static files at the top of the template:
{% load static %}
My Django Site
Welcome to My Django Site