Static files like images, styles, and scripts make websites look good and work well. Managing them properly helps your site load faster and stay organized.
0
0
Why static file management matters in Django
Introduction
When you want to add images or logos to your website.
When you need to apply styles using CSS files.
When you want to include JavaScript for interactive features.
When preparing your website for deployment to a live server.
When organizing your project files to keep code and assets separate.
Syntax
Django
In Django settings.py: STATIC_URL = '/static/' STATICFILES_DIRS = [BASE_DIR / 'static'] In templates: {% load static %} <link rel="stylesheet" href="{% static 'css/style.css' %}">
Use STATIC_URL to tell Django where static files live in URLs.
Use the {% static %} template tag to link static files in HTML.
Examples
This sets the base URL path for static files.
Django
STATIC_URL = '/static/'Load the static tag and use it to include an image in a template.
Django
{% load static %}
<img src="{% static 'images/logo.png' %}" alt="Logo">Tell Django to look for static files in a custom folder named 'assets'.
Django
STATICFILES_DIRS = [BASE_DIR / 'assets']Sample Program
This example shows how to set up static file paths in Django settings and use them in an HTML template to include CSS and images.
Django
settings.py: from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent STATIC_URL = '/static/' STATICFILES_DIRS = [BASE_DIR / 'static'] In template.html: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="{% static 'css/style.css' %}"> <title>Static Files Example</title> </head> <body> <h1>Welcome!</h1> <img src="{% static 'images/logo.png' %}" alt="Site Logo"> </body> </html>
OutputSuccess
Important Notes
Always run python manage.py collectstatic before deploying to gather all static files in one place.
Keep static files organized in folders like css, js, and images for clarity.
Using the {% static %} tag helps avoid broken links when moving between development and production.
Summary
Static files are important for website look and feel.
Django needs to know where to find and serve these files.
Proper management keeps your site fast and organized.