Example of a template

For this example, we will use the example from the Variables lesson. We already know some of these steps, but we will go through them once again to help reinforce the concepts.

We need to perform the following steps:

Step 1: Create a templates directory

First, we will create a templates directory in the outermost first_project directory. Then, inside the templates directory, we will add another directory by the name of our application, called first_app, such that the hierarchy becomesfirst_project/templates/first_app/.

Step 2: Tell Django where to find templates

As we saw in the previous lesson, we have to use the os module to feed path to the DIR key. First, we will open settings.py in our project’s directory. In settings.py, we will see a variable by the name of BASE_DIR. This variable basically builds the paths inside of the project. If we print the value of BASE_DIR, it will print out the project directory, which contains manage.py and application folders. We can use this BASE_DIR variable to refer to our new templates directory. In order to do this, add the following line below the BASE_DIR line:

TEMPLATE_DIR= os.path.join(BASE_DIR,"templates")

In the example above, the TEMPLATE_DIR variable holds the absolute path to the location of the templates folder inside of our project.

Now, scroll down, and we will see the TEMPLATES dictionary, in which we will see a key with the name of DIRS. Just pass the variable we created above, TEMPLATE_DIR, in the value of DIRS. Together, they will look like this:

Get hands-on with 1200+ tech skills courses.