Introduction to Templates
Till now, you have learned how to create a view that takes a web request and returns an HTTP response.
Now, we are going to learn how to render HTML page from our django view.
In Django, there is Django Template Engine which is installed by default.
The Django template engine is a built-in feature of the Django web framework that allows developers to specify the structure of an HTML page and replace placeholders with dynamic content.
The template engine takes a template file and a dictionary-like object usually named as context that contains the values to be used in the template, and returns the resulting string with the placeholders replaced by the corresponding values.
Lets see how to use the Django Template Engine.
First of all, create a folder in the root directory named templates and create a sub-folder named mysite. In this folder, we are going to store the HTML files.
Now, open the settings.py file and configure the template directory.
Under templates update the DIR value as
'DIRS': [BASE_DIR / "templates"],
In this way, we have configured the html template location so that Django Template Engine can discover our HTML files.
Now, open mysite.views.
To render HTML page, we need to import render method from django.shortcuts
from django.shortcuts import render
Now, create a context dictionary having a message key.
context = {
"message": "Hello Django Developers"
}
After that return the render method.
return render(request, "mysite/index.html", context)
- This render method takes request as first argument.
- In the second argument, we need to provide the location of HTML file which we will create in the mysite folder of templates directory.
- In the third argument, provide the context which you want to pass in to the HTML file.
Now, create one HTML file named index.html inside mysite folder of templates.
Add this code in the HTML file.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
This is an index page.
</body>
</html>
Now, start the development server and visit 127.0.0.1:8000
You will see something like this.

Now, remember in the index view we have provided context dictionary where we created a key named "message".
So, in the html file, let us add that message.
{{ message }}
In this way, you can add a string in the HTML file that is stored in the context dictionary.
Now, open the browser and see the changes.
You will see something like this.

In this way, we have learned how to use django template engine to render HTML file from our django view.