Skip to main content

Chapter 2. Template System

📄️ Introduction to the Template System

In the previous chapter we saw how to construct HTML code from a view and return it as the content of a response via the django.http.HttpResponse class. However, this procedure of including HTML code within Python code becomes problematic when you start working with real web applications, where HTML code is often voluminous and some of it is repeated on many pages. Furthermore, it is not a good practice to mix two very different concepts of an application: the logical component (Python code) and the graphical component (HTML).

📄️ 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.

📄️ Addendum: Pattern Matching in URLs

In previous sections, we have created the /courses URL and bound it to the courses() view, which displayed a list of courses stored in courses.db. Now suppose that you want to create a course() view where the details of a particular course are displayed. For this, you could configure a /course URL followed by the name of the course from which you want to return the information, for example, /course/Python, /course/Java, /course/PHP, etc. Let's do it so by adding that configuration to our myapp/urls.py file: