Updated May 3, 2023
Introduction to Django Templates
To understand and operate the process of Django applications, these templates play a major role; all static items in a web page designed with Django hold the templates for constructing the static entities. In other words, it could be described that the templates are responsible for building the skeleton of a webpage. These templates make a Django setup an MVT-oriented architecture. M stands for the models involved, V stands for the views designed, and T refers to the templates. On Standard ways, the templates used in a Python setup are rendered using a Django view.
Using Templates to Render Django Views
Given below are the templates to render Django views:
1. Create a template folder
All template-related HTML code could be placed into this folder. The template folder has to be created under the primary project folder.
2. Tag the template folder in settings.py file
The settings.py file is used for tagging these templates to their associated views. When the tagging process is accomplished, all the HTML contents placed inside the folder fall under this template section.
Code:
import os
# Build paths inside the project like this: os.path.join(BASE_DIR,...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
Template_DIR = os.path.join(BASE_DIR,'Templates')
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [Template_DIR,],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
,
},
},
]Template_DIR = os.path.join(BASE_DIR,'Templates')
The Python path in the BACKEtemplate’sused to implement the Django template’s API backend. Some backends built-in Django are django.template.backends.django.DjangoTemplates and django.template.backends.jinja2.Jinja2.
- The directory in which the template engine needs to locate the template-related search files is placed in the DIRS directory.
- Whereas the APP_DIRS helps mention the location at which the engine has to verify the templates within the installed applications. Each defined backend provides a conventional name for every subdirectory inside the applications.
3. Place the HTML file inside the templates folder
Code:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Django App1</title>
</head>
<body>
<h1> Hello world from HTML page <h1>
</body>
</html>
Syntax:
render(request,template_name,context=None,content_type=None,status=None,using=None)
Arguments | Description |
request | This is used to generate a response. This is a mandatory argument. |
template name | Name of the template used for this view. This is a mandatory argument. |
context | A context is a variable name and variable value mapping maintained as a dictionary. By default, this is an empty dictionary. So if the key is passed, the corresponding value from the dictionary can be retrieved and rendered. This is an optional argument. If nothing is provided for the context, then render an empty context. |
content_type | MIME(Multipurpose Internet Mail Extensions) to be used. The default value is ‘text/html’. This is an optional argument. |
status | The response code to be used. The default response code is 200. |
using | This argument represents the name of the template engine used for loading the template. This is an optional argument. |
Example: Code:
from django.shortcuts import render
from django.http import HttpResponse
def index(request_iter):
return render(request_iter,'design.html')
4. Tag the view in urls.py file
This is the process of creating a url for the view. The url mentioned here will be used to reach the web page mentioned.
- Import the library from django.conf.urls import url.
- Declare a url entry in the urlpatterns list.
url(url_path,view_to_be_tagged,name_for_this_view)
Example:
Code:
from django.contrib import admin
from django.conf.urls import url
from Django_app1 import views
urlpatterns = [
url(r'^$',views.index,name='index'),
url(r'admin/',admin.site.urls),]
5. Reload the server using the python manage.py runserver command and verify webpage
The system message below will be printed in the project console on loading the runserver. This message contains detailed information about when the server was started, the Django version used, and the HTTP link at which the server was kickstarted.
Code:
Watching for file changes with StatReloader
Performing system checks...
System check identified no issues (0 silenced).
June 10, 2020 - 11:23:00
Django version 3.0.7, using settings 'educba.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
Output:
Django View Rendered from Template Tag
Given below is the Django view rendered from the template tag:
1. The template tags inject dynamically generated content into the Django views. This is among the key functionalities of template tags. They could flexibly inject dynamic content into the file.
The template tag filters could use the below-listed options:
All Options in the Template Filters | ||
add | addslashes | capfirst |
center | cut | date |
default | dictsort | divisibleby |
escape | filesizeformat | first |
join | last | length |
linenumbers | lower | make_list |
random | slice | slugify |
time | timesince | title |
unordered_list | upper | wordcount |
2. In this example, we added the if and filter tags to the template.
- Add a template tag in the HTML file.
Code:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Django App1</title>
</head>
<body>
<h1> <u> All valid Technical tutorials </u> </h1>
{% if Entity_type == 'tutorial' %}
{{ Entity_name }}
{% else %}
{{ Error_Message }}
{% endif %}
<h2> <u> Django filters Explained <u> </h2>
<p> Student Count: {{ Entity_students_count | add:"230"}} <p>
<p> Entity Type: {{ Entity_type | capfirst}} <p>
</body>
</html></html></html>
Example:
from django.shortcuts import render
from django.http import HttpResponse
def index(request_iter):
dict_Var = {
"Entity_name": "Educba",
"Entity_type": "tutorial",
"Entity_students_count": 345,
"Error_Message": "No Valid Entity found"
}
return render(request_iter,'design.html',context=dict_Var)
3. Reload the server using the python manage.py runserver command and verify the webpage.
Output:
Conclusion
The use of templates is one among the biggest capabilities of Django in the web development framework. These templates allow the Django setup to flexibly transfer dynamic content between the front end and the middle stream.
Recommended Articles
We hope that this EDUCBA information on “Django Templates” was beneficial to you. You can view EDUCBA’s recommended articles for more information.