Django Static Files
What is Static Files in Django?
Serving static files like CSS, JavaScript, and images is an essential part of web development.
Configuring static file directories:
To begin with, you need to define the location of your static files on your local directories.
In your Django project settings (settings.py), you'll see STATIC_URL variable, along with extra data, pointing to the prefix URL that points to static files.
In addition to those, you need a STATICFILES_DIRS definition, which is a list of directories where static files are going to be looked for by Django.
# settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
In this example, we're telling Django to look for static files in a directory called static within our project directory.
Serving static files:
After all configurations of static file directories are done, you should be serving them during the development.
Say, in the main urls.py file of your project, you can add a URL pattern which will serve your static files using Django's static() function which is a built-in one.
# urls.py
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# Your URL patterns here
]
# Serve static files during development
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
This code ensures that Django serves static files when you're running your project in debug mode (DEBUG=True).
Linking static files in templates:
in your HTML templates, you can link to static files using the {% static %} template tag.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>My Website</title>
<link rel="stylesheet" type="text/css" href="{% static 'css/styles.css' %}">
</head>
<body>
<!-- Your HTML content here -->
</body>
</html>
This tag will generate the correct URL for the static file based on the STATIC_URL setting, allowing Django to serve the file correctly.