Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Template Folder | Templates
Django: First Dive
course content

Course Content

Django: First Dive

Django: First Dive

1. Get Started
2. Write the First Page
3. Models
4. Working with Database
5. Templates
6. Request Handling

bookTemplate Folder

Now let's consider the third part of MVT architecture - Template.

Template is a HTML file with the page structure and specific syntax. The main feature of templates in Django is a technology named Django Template Language (DTL).

The template is processed using DTL syntax before being sent to the user, inserting certain data, and performing other manipulations with the page. It allows you to dynamically generate different HTML pages based on existing templates.

Connect Template Folder

You need to connect the template folder in the settings.py file to use the template files.

In this file, find the TEMPLATES list and write the following:

The TEMPLATES list contains the dictionary with a 'DIRS' key.
Add the os.path.join(BASE_DIR, 'templates'), to the 'DIRS' : [] list.

Create a new folder named templates (or defined folder name in the settings.py file by you).

The default .html file structure:

Let's write the <h1>Hello World from Template!</h1> inside the body tag.

Connect Template to View function

Now, we need to connect this template to the hello_world_view function. In the views.py file (new_app folder), we have the suggested render function:

We can return the template using this function.

The first argument of this function should be received request. The second argument is our HTML template. In this case, a template is the hello_world.html file.

Note

  • The render() function generates the HttpResponse object using the request data and HTML template.
  • Templates are searched in the corresponding directory specified in the settings. If something doesn't work, check the name of the template directory and its name in the settings.py.

Working with strings in Python is not convenient, but now we can create whole structures of HTML documents.

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 5. Chapter 1
some-alt