How to Add CSS and JavaScript to Django (Static Files Guide)

3D isometric illustration of a plain HTML building being painted and animated using files from a 'static' folder.

Your Django site works, but it’s just plain HTML. To make it look professional, you need CSS, JavaScript, and images. For an in-depth Django Static Files Guide, Django calls these static files.

Step 1: Create a static Folder

Just like you made a templates folder, you need a static folder. The standard practice is to create one at the top level of your project (next to manage.py).

/MyProject
    /config
    /pages
    /templates
    /static/  <-- Create this
        css/
            style.css
        images/
            logo.png

Go ahead and create static/css/style.css and add some simple CSS:

/* static/css/style.css */
body {
    background-color: #f0f0f0;
    color: #333;
}

Step 2: Tell Django Where to Look

In your config/settings.py file, you need to tell Django about this new folder.

Find the STATIC_URL line (it’s usually at the bottom) and add STATICFILES_DIRS right below it.

# config/settings.py
STATIC_URL = '/static/'

# Add this line:
STATICFILES_DIRS = [
    BASE_DIR / "static",
]

Step 3: Load Static Files in Your Template

Open your home.html (or any other template).

  1. At the very top, you must load the static library.
  2. Use the {% static %} tag to build the correct URL path.
{% load static %} 


    <title>My Django Site</title>
    <link rel="stylesheet" href="{% static 'css/style.css' %}">


    <h1>Hello, World!</h1>
    <p>This page now has CSS!</p>

Now run your server, and your homepage should have a gray background!

Similar Posts

Leave a Reply