Python and Django Full Stack - Templates
Templates in
Django
Templates can be understood as a skeleton of the page. There
are two parts to a templates file – One, the static information, and two, template
tags, that inject dynamic data with special syntax, through its views, forming
the final HTML.
They are key to understanding how Django interacts with the
website. Later, we will connect templates with models, so data can be created
and displayed dynamically.
1.
Create
a new folder – in the base folder first_project/templates/first_app
2. Let Django know of the templates. Edit
the DIR key inside the settings.py to include ‘templates’.
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['templates',],
'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',
],
},
},
]
3.
Inside first_project/templates/first_app, create an index.html file. It is a good
practice to keep separate template files for separate apps.
<!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>First App</title>
</head>
<body>
<h1>Hello, this is
index.html</h1>
{{insert_me}} // template tags aka
Django template variable.
</body>
</html>
The template tag will allow us to inject
content into HTML directly.
4.
Open first_project/first_app/views.py
from django.shortcuts import render
#
Create your views here.
def
index(request):
my_dict =
{
'insert_me':'Hello I am from first_app/index.html ' //
This is the template we want to use.
}
return render(request, 'first_app/index.html', context=my_dict)
Notice that we did away with HttpResponse, and will
now use render.
The statement
“render(request,
'first_app/index.html', context=my_dict)” links this view to the index html we
created.
The host server will now show

Comments
Post a Comment