Welcome to our comprehensive guide on working with Static Files in Templates using Django! By the end of this tutorial, you'll be able to serve static files like CSS, JavaScript, and images in your Django projects. Let's dive right in!
Static files are resources like images, CSS files, JavaScript files, and media that don't change often and are used to enhance the appearance, functionality, or behavior of our web application.
In Django, we have a pre-built solution for handling static files.
Before we dive into the code, let's first understand the project structure for our static files.
myproject/
...
myapp/
...
static/
css/
js/
images/
...
In the above project structure, we have created a static folder inside our app (myapp). Inside the static folder, we have separate folders for CSS, JavaScript, and Images.
Now, let's see how to serve these static files in our Django templates.
To include static files in our templates, we first need to add the {% load static %} line at the beginning of our template file.
{% load static %}
<!DOCTYPE html>
<html>
<head>
<title>My First Django Template</title>
<link rel="stylesheet" type="text/css" href="{% static 'css/styles.css' %}">
</head>
<body>
<!-- Rest of the template -->
</body>
</html>In the above example, we are including a CSS file named styles.css located inside the css folder in our app's static folder.
When we make changes to our static files, Django doesn't automatically update the served files. To update the served files, we need to run the collectstatic command.
python manage.py collectstaticThis command collects all the static files from the various apps in our project and puts them in a single location. By default, Django will place these files in the STATIC_ROOT directory.
Where does Django place the collected static files by default?
That's it for our tutorial on Static Files in Templates using Django! You now know how to set up static files, include them in templates, and collect them for serving.
In the next lesson, we'll dive deeper into working with media files in Django. Stay tuned!
π‘ Pro Tip: Make sure to add STATIC_URL in your Django project's URL patterns to serve the static files correctly.
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# Your URL patterns here
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)