Static Files
JavaScript and CSS files, images, PDF documents, etc., are known as static files in web development. In general, any file whose content is not generated in real time in each request is a static file. There are several reasons why these files receive special treatment. One of them is that, once a Django project is set up in production, you will want the static files to be served directly by the web server, not by the framework. We will look at this in more detail in the last chapter. To make this possible, you will have to use a special tag in the templates every time we refer to a static file.
First of all, we are going to place the static files inside the myapp/static/myapp/
directory. Download the django.png
image from this link and store it as myapp/static/myapp/django.png
. Now, if you want to display it in the index.html
template, do the following:
{% load static %}
<html>
<h1>List of students</h1>
<img src='{% static "myapp/django.png" %}' />
...
</html>
The important thing about this code is:
- the first line, which indicates that the
static
tag is going to be used (this is necessary since it is not a tag defined by Django, but by an application that is installed by default), and - the fourth line, where the
static
tag is used to generate a URL to thestatic/myapp/django.png
file.
The generated result is the following:
You might need to reload Django's development server (i.e., execute python manage.py runserver
again) for static assets to start working.
The same works for CSS and JavaScript files. Let's look at an example. In our templates/myapp/courses.html
file we had this line:
<table style="border: 1px solid">
But it's not good practice to include CSS code in an HTML file, so let's move the style from that table to a new static/myapp/styles.css
file:
.courses-table {
border: 1px solid;
background-color: lightpink; /* New background color */
}
Now you to load this file from courses.html
. Do it so by using the HTML link
tag and the Django static
tag as we did previously (changed code highlighted):
{% load static %}
<html>
<head>
<title>Courses List</title>
<link rel="stylesheet" type="text/css" href='{% static "myapp/styles.css" %}'>
</head>
<table class="courses-table">
<thead>
<tr>
<th>Course</th>
<th>Students</th>
</tr>
</thead>
{% for name, enrolled_students in courses %}
<tr>
<td>{{ name }}</td>
<td>{{ enrolled_students }}</td>
</tr>
{% endfor %}
</table>
</html>