STATIC_URL and STATICFILES_DIRS help Django find and serve your static files like images, CSS, and JavaScript. They make your website look and work nicely.
0
0
STATIC_URL and STATICFILES_DIRS in Django
Introduction
When you want to add images or styles to your website.
When you have JavaScript files to make your site interactive.
When you want to organize static files in different folders.
When you need Django to know where to find your static files during development.
When you want to serve static files in production after collecting them.
Syntax
Django
STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / 'static', ]
STATIC_URL is the web address prefix for static files.
STATICFILES_DIRS is a list of folders where Django looks for static files.
Examples
This changes the URL prefix to '/assets/' and tells Django to look in the 'assets' folder for static files.
Django
STATIC_URL = '/assets/' STATICFILES_DIRS = [ BASE_DIR / 'assets', ]
Django will look in both 'static' and 'extra_static' folders for static files.
Django
STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / 'static', BASE_DIR / 'extra_static', ]
Sample Program
This example sets up STATIC_URL and STATICFILES_DIRS using BASE_DIR. It prints the URL prefix and the list of folders where Django will look for static files.
Django
from pathlib import Path BASE_DIR = Path(__file__).resolve().parent STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / 'static', ] print(f"Static URL is: {STATIC_URL}") print(f"Static files directories: {STATICFILES_DIRS}")
OutputSuccess
Important Notes
Always end STATIC_URL with a slash '/' to avoid URL problems.
STATICFILES_DIRS is optional if you only use app static folders.
In production, use collectstatic to gather all static files in one place.
Summary
STATIC_URL sets the web path prefix for static files.
STATICFILES_DIRS tells Django where to find extra static files outside apps.
These settings help your website load images, styles, and scripts correctly.