Previous Page Next Page

Creating a Template

Django templates can combine a Django placeholder and just about any type of raw text code that displays a web page. Django placeholders are designated by encapsulating them in double braces:

{{ person_name }}

The raw text portion of the file can contain various types of information. The best way to explain this is with some examples. The following sections take you through some different methods of creating and using Django templates.

Creating Templates in the Django Shell

The first example we will look at is using Django templates in the Django shell to format text output. You probably won't use templates in the shell. However, the shell is a great place to learn about them and try them out.

To create a template in the Django shell, first import the Template object class from the django.template project using the following command:

from django.template import Template

By the Way

You can use the following command from the root of your project to start the Django shell:

python manage.py


You create a template by calling the constructor of the Template class and passing in a string containing a placeholder. For example, the following line of code defines a Template object t that contains a variable placeholder emotion:

t = Template("I feel {{emotion}}.")

Next, you create some Context objects by calling the Context() constructor and passing it a dictionary that contains the emotion key:

from django.template import Context
c1 = Context({'emotion': 'happy'})
c2 = Context({'emotion': 'fine'})
c3 = Context({'emotion': 'good'})

By the Way

You can change the contents of Context by treating it as a Python dictionary. For example, to change the emotion of the c1 Context object in the preceding example, you could use the following line of code:

c1['emotion'] = 'cool'


After you have created the Template and Context objects, you can render the template to text by calling the render() function of the Template object and passing the appropriate context, as shown in Figure 7.1.

Figure 7.1. Creating and rendering a template in the Django shell.


The render() function reads the dictionary in the context and replaces variable placeholders in the template that match keys in the dictionary with the key's value.

Did you Know?

If you have a lot of text that needs to be processed as a template, you can store the template text as a text file and then use Python's file functions to read in the contents of the template as a string. This also works when you use the Django shell to test your HTML templates. For example, to read the contents of a myTemplate.html file into a Template object, you could use the following line of code:

myT = Template(open('myTemplate.html', 'rU').read())


Creating HTML Templates

Most of the templates you will work with in your Django website will be HTML templates. HTML templates are text files that contain mostly HTML code but do contain some variable placeholders. You will be able to render the HTML template, using custom contexts, as a response to an HTTP request. Using this method, you can write your web pages using basic HTML tags but still can programmatically control the variable content.

The best way to create an HTML template is to first create an HTML file with the look and feel that you like and test it in a web browser. Then add the variable placeholders for data that needs to be dynamic. For example, test.html, shown in Listing 7.1, displays the simple web page shown in Figure 7.2.

Listing 7.1. Full Contents of the test.html File

<html xmlns="http://www.w3.org/1999/xhtml" lang="en-us" xml:lang="en-us" >
<head>
<title>Title</title>
</head>
<body>
<table width=100%>
<tr bgcolor="aabbcc"><td colspan="2">
<font size="12" color="white">Title</font>
</td></tr>
<tr valign="top"><td width=70% bgcolor="aaaaaa"><font color="white" size="5">
    <H2>Headline</H2>
    data
</font></td>
<td width=30%>
    <h3>Current Time</h3>
    time
</td></tr>
</table>
</body>
</html>


					  

Figure 7.2. Web page generated by test.html.


To turn test.html into a Django template, you would replace the dynamic items Title, Headline, data, and time with the following variable placeholders, as shown in Listing 7.2:

{{ title}}, {{ headline }}, {{ data }} and {{time}}

Listing 7.2. Full Contents of the Modified test.html File

<html xmlns="http://www.w3.org/1999/xhtml" lang="en-us" xml:lang="en-us" >
<head>
<title>{{ title }}</title>
</head>
<body>
<table width=100%>
<tr bgcolor="aabbcc"><td colspan="2">
<font size="12" color="white">{{ title }}</font>
</td></tr>
<tr valign="top"><td width=70% bgcolor="aaaaaa"><font color="white" size="5">
    <H2>{{ headline }}</H2>
    {{ data }}
</font></td>
<td width=30%>
    <h3>Current Time</h3>
    {{ time }}
</td></tr>
</table>
</body>
</html>


					  

With the variable placeholders in the test.html file, Django enables you to deliver dynamic web pages based on different contexts. For example, the following code snippet creates a context that generates the web page shown in Figure 7.3:

c = Context()
c['title'] = 'My Log'
c['headline'] = 'Entry #5'
c['data'] = 'Found errors in subroutines 2, 5 and 8.'
from datetime import datetime
c['time'] = datetime.now()

Figure 7.3. Web page generated by context using the My Log code snippet.


To change the content that Django places in the web page, all that needs to happen is for the data in the context to change. For example, the following code snippet creates a context that generates the web page shown in Figure 7.4:

c = Context()
c['title'] = 'Corporate Memos'
c['headline'] = 'Company Party'
c['data'] = 'There will be a company Party on Friday. '
c['data'] += 'Families are invited.'
from datetime import datetime
c['time'] = datetime.now()

Figure 7.4. Web page generated by context using the Corporate Memos code snippet.


Accessing Objects Using HTML Templates

Django's template parser allows you to access object fields directly from the template. This is a major advantage, because most of the data you will display in the web pages will be in the form of objects that were queried from the database. Instead of having to add each field as an entry in the Context dictionary, you only need to add the object.

Django uses the . (dot) syntax in the variable placeholder to access fields in the object. For example, to access the title field of a Blog object, you would use the following variable placeholder:

{{ blog.title }}

By the Way

If the value of the field is also an object, you can access the fields of the subobject as well. For example, if the Person object has a field blogs that refers to a list of Blog objects, you could access the title field of the first Blog object using the following syntax:

{{ person.blogs[0].name }}


Try It Yourself: Create an HTML Template for a Details View

In this section, you will create an HTML template for the details view of a Person object in the iFriends project. You will first create the HTML file, and then you will add the variable placeholders to dynamically display details of the Person object.

Follow these steps to create an HTML document to display Person details and turn it into a Django template:

1.
Using a text editor, create a file called person_details.html, and place the code shown in Listing 7.3 in it. The file should generate a web page similar to the one shown in Figure 7.5.

Listing 7.3. Full Contents of the person_details.html HTML Document

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en-us" xml:lang="en-us" >
<head>
<title>Test Page</title>
</head>
<body>
<table width=100%>
<tr bgcolor="aabbcc"><td colspan="3">
<font size="12" color="white">Personal Information</font>
</td></tr>
<tr valign="top"><td width=30% bgcolor="aaaaaa"><font color="white" size="5">
    <li>Name: name</li>
    <li>Birthday: birthday</li>
    <li>Gender: gender</li>
    <li>Desc: desc</li>
</font></td>
<td width=40% bgcolor="aa99aa"><font color="white" size="4">
    <p align="center">Comments</p>
    <p align="center">None.
</font></td>
<td width=30%>
    <h3>Contact Info</h3>
    <li>Email: email</li>
    <li>Website: website</li>
</td></tr>
</table>
</body>
</html>


					  



Figure 7.5. Web page generated by person_details.html.


2.
Modify the following line from Listing 7.3 to match Listing 7.4 to display the person's name in the title bar of the web browser:

<title>Test Page</title>

It becomes

<title>{{ p.name }}</title>

3.
Modify the following lines from Listing 7.3 to match Listing 7.4 to display the person's details in the details section of the web browser:

<li>Name: name</li>
<li>Birthday: birthday</li>
<li>Gender: gender</li>
<li>Desc: desc</li>

They become

<li>Name: {{p.name}}</li>
<li>Birthday: {{ p.birthday }}</li>
<li>Gender: {{ p.gender }}</li>
<li>Desc: {{ p.desc }} </li>

4.
Modify the following lines from Listing 7.3 to match Listing 7.4 to display the person's contact information in the contact section of the web browser:

<li>Email: email</li>
<li>Website: website</li>

They become

<li>Email: {{ p.email }}</li>
<li>Website: {{ p.favoriteURL }}</li>

5.
Save the new file. (It is shown in Listing 7.4.)

6.
Copy the person_details.html file to the iFriends/templates/People template directory for the People application of the iFriends project.

Listing 7.4. Full Contents of the Modified person_details.html Django Template

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en-us" xml:lang="en-us" >
<head>
<title>{{ p.name }}</title>
</head>
<body>
<table width=100%>
<tr bgcolor="aabbcc"><td colspan="3">
<font size="12" color="white">Personal Information</font>
</td></tr>
<tr valign="top"><td width=30% bgcolor="aaaaaa"><font color="white" size="5">
    <li>Name: {{p.name}}</li>
    <li>Birthday: {{ p.birthday }}</li>
    <li>Gender: {{ p.gender }}</li>
    <li>Desc: {{ p.desc }} </li>
</font></td>
<td width=40% bgcolor="aa99aa"><font color="white" size="4">
    <p align="center">Comments</p>
    <p align="center">None.
</font></td>
<td width=30%>
    <h3>Contact Info</h3>
    <li>Email: {{ p.email }}</li>
    <li>Website: {{ p.favoriteURL }}</li>
</td></tr>
</table>
</body>
</html>


					  


Previous Page Next Page