Previous Page Next Page

Hour 7. Implementing Django Templates to Create Custom Views

What You'll Learn in This Hour

  • How to configure the template directory for a project

  • How to create templates in the Django shell

  • How to render views using templates

  • How to extend templates

  • How to embed templates in other templates

So far, all the examples of web pages that you have created in your views have been hard-coded by Python code that generates an HTML web page. This has worked well because the web pages that you have created have been basic.

As you create more advanced web pages, you will want to begin using the Django template system. The Django template system allows you to write template files that define the presentation of the web page independent of the data. This means that you can write generic web pages and then use the Python code in the views to generate dynamic content inside them.

Using the template system has several benefits. For example, an HTML developer could be working on the web page views, and a Python developer could be working on processing the data at exactly the same time.

In this hour, you will get a chance to create some HTML templates and use them to render the data in your views.

Configuring the Template Directory

The first step in adding templates to your website is to create and configure a directory to store them in. You will want to create at least one directory to store the templates in and then add that directory to the TEMPLATE_DIRS setting in the project's settings.py file.

Django's template engine will read the TEMPLATE_DIRS setting and use the directories that are configured there to process the relative paths you will specify for the template.

Try It Yourself: Create and Configure a Template Directory for a Project

In this section, you will create a template directory in the root of the iFriends project and then configure Django to search that directory when trying to find templates.

Did you Know?

The Django admin interface uses templates extensively to display the admin web pages. The admin template directory is built into the template search path and doesn't need to be specified in the TEMPLATE_DIRS setting in the settings.py file. The admin template directory is located in the following path relative to where Django is installed:

django/contrib/admin/templates


Follow these steps to create the directory and modify the settings.py file:

1.
Create a new directory named templates in the iFriends/ directory.

2.
Open the settings.py file in an editor.

3.
Add the full path of the templates directory created in step 1 to the TEMPLATE_DIRS setting:

TEMPLATE_DIRS = (
    # Put strings here, like "/home/html/django_templates" or
    # "C:/www/django/templates".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
    "C:/websites/iFriends/templates",
)

4.
Save the settings.py file.


Previous Page Next Page