Django - Add CSS Files



CSS (Cascading Style Sheets) is an important component of the World Wide Web alongside HTML and JavaScript. It is a style sheet language used for specifying the presentation and styling of a document written in HTML.

CSS Files are Static Assets

In Django, CSS files are termed as static assets. They are placed in the static folder which is created inside the app’s "package" folder.

The static assets are made available with the following template tag

{% load static %}

Normally, the CSS file is included in the HTML code with the following statement, usually placed in the <head> section.

<link rel="stylesheet" type="text/css" href="styles.css" />

However, to include CSS as a static resource, its path is mentioned with {% static %} tag as follows −

<link rel="stylesheet" type="text/css" href="{% static 'style.css' %}">

Applying CSS to the Name of Cities

Here we will show how you can apply CSS to the name of cities displayed as an unordered list in the web page.

Let us define the following index() view that passes a list of cities as a context to a "cities.html" template

from django.shortcuts import render

def index(request):
   cities = ['Mumbai', 'New Delhi', 'Kolkata', 'Bengaluru', 'Chennai', 'Hyderabad']
   return render(request, "cities.html", {"cities":cities})

cities.html

In the "cities.html" template, we first load the CSS file in the HEAD section. Each name is rendered in the <li> . . </li> tag with the help of a for loop template tag.

<html>
<head>
   {% load static %}
   <link rel="stylesheet" type="text/css" href="{% static 'style.css' %}">
</head>
<body>
   <h2>List of Cities</h2>
   <ul>
      {% for city in cities %}
         <li>{{ city }} </li>
      {% endfor %}
   </ul>
</body>
</html>

style.css

We shall apply background color to the webpage and set its font size and color.

Save the following code as "style.css" and put it in the static folder.

h2 {
   text-align: center;
   font-size:xx-large; 
   color:red;
}

ul li {
   color: darkblue;
   font-size:20;
}

body {
   background-color: violet;
}

Register the index() View

The index() view is registered in the urlpatterns of the Django app as follows −

from django.urls import path
from . import views

urlpatterns = [
   path("", views.index, name="index"),
]

The http://localhost:8000/myapp/ URL displays the list of cities according to the above styles −

Django Add CSS Files
Advertisements