Django Templates

Suman Prasad
3 min readMay 3, 2021

--

Django Templates- Learn To Create Your First Template

It is not recommended to write “HTML” inside Python Script (views.py file)

It is because:

  1. It reduces readability of code.
  2. No clear separation of roles. Python developer has to concentrate on both Python Code and HTML Code.
  3. It does not promote reusability of code.

We can overcome these problems by separating HTML Code into a separate HTML file. This HTML file is nothing but template.

From the Python file (views.py) we can use these templates based on our requirement.

We have to write templates at project level only once and we can use these in multiple applications.

PYTHON STUFF REQUIRED TO DEVELOP TEMPLATE BASE APPLICATIONS

  1. To know the current python file name

print(__file__)

2. To know absolute path of current python file name

import os

print(os.path.abspath(__file__))

3. To know Base Directory name of the current file

import os

print(os.path.dirname(os.path.abspath(__file__)))

4.Inside that directory there is one folder name with templates. To Know its absolute path

import os

BASE_DIR=os.path.dirname(os.path.abspath(__file__))

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

print(TEMPLATE_DIR)

Note: The main advantage of this approach is we are not required to hard code system specific paths(locations) in our path script.

STEPS TO DEVELOP TEMPLATE BASED APPLICATION

  1. Creation of Project

django-admin startproject templateproject

2. Creation of Application]

py manage.py startapp testapp

3. Add this application to the project in settings.py file so that Django aware of application.

4. Create a ‘templates’ folder inside main project folder

In that templates folder create a separate folder name with testApp to hold that particular application specific templates.

5) Add templates folder to settings.py file so the Django can aware of our templates

TEMPLATES = [

{

…,

‘DIRS’:[‘D\djangoprojects\templateproject\templates’],

},]

NOTE: It is not recommended to hard code system specific locations in “settings.py” file. To overcome this problem, we can generate templates directory path programmatically as follows.

import os

BASE_DIR=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

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

specify this “TEMPLATE_DIR” inside “settings.py” as follows

TEMPLATES = [

{

…,

‘DIRS’:[TEMPLATE_DIR],

},]

6) Create HTML file inside templateproject/templates/testApp folder. This html file is nothing but template.

testing.html

Figure -1

7) Define Function base view inside views.py file

Figure-2

8) Define URL Pattern either at application level or at project level.

Figure-3

9) Run Server and send request.

py manage.py runserver

--

--

Suman Prasad
Suman Prasad

Written by Suman Prasad

Masters In Data Science @Central University Of Rajasthan. #datascientistenthusiast

Responses (1)