Django Tutorial: Static Files in Templates πŸ“

beginner
11 min

Django Tutorial: Static Files in Templates πŸ“

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!

Understanding Static Files πŸ’‘

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.

Setting up Static Files in Django 🎯

In Django, we have a pre-built solution for handling static files.

Project Structure πŸ“

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.

Serving Static Files in Templates πŸ“

Now, let's see how to serve these static files in our Django templates.

Step 1: Include Static Files in Template βœ…

To include static files in our templates, we first need to add the {% load static %} line at the beginning of our template file.

html
{% 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.

Step 2: Collecting Static Files πŸ’‘

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.

bash
python manage.py collectstatic

This 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.

Quiz Time 🎯

Quick Quiz
Question 1 of 1

Where does Django place the collected static files by default?

Wrapping Up πŸ“

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.

python
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)