It is not recommended to write html code inside python script (views.py file) because:
1) It reduces readability because Python code mixed with html code
2) No seperation 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 seperating html code into a seperate html file.This
html file is nothing but template.
From the Python file (views.py file) 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 Based
Application:
1) To know the current Python file name
print(__file__) #test.py
2) To know absolute path of current Python File Name
import os
print(os.path.abspath(__file__))
Output: D:pythonpowertest.py
3) To know Base Directory name of the current file
print(os.path.dirname(os.path.abspath(__file__)))
Output: D:pythonpower
4) InsideD:pythonpower classes there is one folder named 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)
Output: D:pythonpowertemplates
Note: The main advantage of this approach is we are not required to hard code system
specific paths (locations) in our python 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 seperate folder named with testApp to hold that
particular application specific templates.
5) Add templates folder to settings.py file so that Django can aware of our templates.
TEMPLATES = [
{
‘DIRS’: [‘D:djangoprojectstemplateProjecttemplates’],
},]
It is not recommended to hard code system specific locations in settings.py file. To
overcome this problem, we can generate templates directory path programatically 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
{
‘DIRS’: [‘TEMPLATE_DIR’],
6) Create html file inside templateProject/templates/testApp folder. This html file is
nothing but template.
wish.html:
1) <!DOCTYPEhtml> |
2) <htmllang=“en”dir=“ltr”> |
3) <head> |
4) <meta charset=“utf-8”> |
5) <title>First Template Page</title> |
6) </head> |
7) <body> |
8) <h1>Hello welcome to Second Hero of MVT: Templates</h1> |
9) </body> |
10) </html> |
1) from django .shortcuts import render |
2) def wish(request): |
3) return render(request,‘testApp/wish.html’) |
9) Run Server and send Request.
Template Tags:
From Python views.py we can inject dynamic content to the template file by using
template tags.
Template Tags also known as Template Variables.
Take special care about Template tag syntax it is not python syntax and not html syntax.
Just it is special syntax.
Template Tag Syntax for inserting Text Data: { {insert_date} }
This template tag we have to place inside template file (ie html file) and we have to
provide insert_date value from python views.py file.
Application to send Date and Time from views.py to
Template File:
wish.html
1) <!DOCTYPEhtml> |
2) <htmllang=“en”dir=“ltr”> |
3) <head> |
4) <meta charset=“utf-8”> |
5) <title>First Template Page</title> |
6) <style > |
7) h1{ |
8) color : white; |
9) background: red; |
10) } |
11) </style> |
12) </head> |
13) <body> |
14) <h1>Hello Server Current Date and Time : <br> |
15) {{insert_date}} |
16) </h1> |
17) </body> |
18) </html> |
views.py
1) from django .shortcuts import render |
2) import datetime |
3) def wish(request): |
4) date=datetime.datetime.now() |
5) my_dict={‘insert_date’:date} |
6) return render(request,‘testApp/wish.html’,context=my_dict) |
Note: The values to the template variables should be passed from the view in the form of
dictionary as argument to context.
Application To display date, time and student information:
views.py
1) from django. shortcuts import render |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
2) import datetime |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
3) |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
4) #Create your views here. |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
5) def template_view(request): |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
6) dt=datetime.datetime.now() |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
7) name=‘pythonpower’ |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
8) rollno=101 |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
9) marks=100 |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
10) my_dict={‘date’:dt,‘name’:name,‘rollno’:rollno,‘marks’:marks} |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
11) return render(request,‘testapp/results.html’,my_dict) results.html
|
Working with Static Files:
. Up to this just we injected normal text data into template by using template tags.
. But sometimes our requirement is to insert static files like images,css files etc inside
template file.
Process to include Static Files inside Template:
. Create a folder named with ‘static’ inside main project folder. It is exactly same as
. creating ‘templates’ folder.
. In that ‘static’ folder create ‘images’ folder to place image files.
. Add static directory path to settings.py file, so that Django can aware of our images.
settings.py
1) STATIC_DIR=os.path.join(BASE_DIR,‘static’) |
2) |
3) .. |
4) STATIC_URL=‘/static/’ |
5) |
6) STATICFILES_DIRS=[ |
7) STATIC_DIR, |
8) ] |
http://127.0.0.1:8000/static/images/divine3.jpg
5) Use Template Tags to insert image
At the beginning of HTML just after <!DOCTYPE html> we have to include the following
template tag. {% load staticfiles %}
Just we are conveying to the Django to load all static files.
We have to include image file as follows. <img src=”{% static “images/divine3.jpg”% }”>
wish.html
1) <!DOCTYPEhtml> |
2) {%load staticfiles %} |
3) <htmllang=“en”dir=“ltr”> |
4) <head> |
5) <meta charset=“utf-8”> |
6) <title>First Template Page</title> |
7) <style > |
8) #h11{ |
9) color:red; |
10) } |
11) #h12{ |
12) color : green; |
13) } |
14) </style> |
15) </head> |
16) <body> |
17) <h1 id=h11>{{insert_msg}}</h1> |
18) <h1 id=h12>Current Date and Time : {{insert_date}}</h1> |
19) <h1>This climate preferable image is:</h1> |
20) <img src=”{% static “images/divine3.jpg” %}” alt=“”> |
21) </body> |
22) </html> |
views.py
1) from django .shortcuts import render |
2) import datetime |
3) |
4) #Create your views here. |
5) def wish(request): |
6) date=datetime.datetime.now() |
7) msg=None |
8) h=int(date .strftime(‘%H’)) |
9) if h<12: |
10) msg=‘Hello Guest !!!! Very Very Good Morning!!!’ |
11) elif h<16: |
12) msg=‘Hello Guest !!!! Very Very Good AfterNoon!!!’ |
13) elif h<21: |
14) msg=‘Hello Guest !!!! Very Very Good Evening!!!’ |
15) else: |
16) msg=‘Hello Guest !!!! Very Very Good Night!!!’ |
17) my_dict={‘insert_date’:date,‘insert_msg’:msg} |
18) return render(request,‘testApp/wish.html’,context=my_dict) |
How to include CSS File:
1) Create a folder ‘css’ inside static and place our demo.css file in that css folder.
demo.css
1) img{ |
2) height: 500px; |
3) width: 500px; |
4) border: 10px red groove; |
5) margin:0% 20%; |
6) } |
7) h1{ |
8) color:blue; |
9) text-align: center; |
10) } |
2) In the template html file we have to include this css file. We have to do this by using
link tag inside head tag.
<link rel=”stylesheet” href=”{% static “css/demo.css” %}” >
index.html
1) <!DOCTYPEhtml> |
||||||||||||||||||||
2) {%load static files %} |
||||||||||||||||||||
3) <htmllang=“en”dir=“ltr”> |
||||||||||||||||||||
4) <head> |
||||||||||||||||||||
5) <meta charset=“utf-8”> |
||||||||||||||||||||
6) <title></title> |
||||||||||||||||||||
7) <link rel=“stylesheet” href=”{% static “css/demo.css”%}”> |
||||||||||||||||||||
8) </head> |
||||||||||||||||||||
9) <body> |
||||||||||||||||||||
10) <h1>Welcome to Python Power</h1> |
||||||||||||||||||||
11) <ul> |
||||||||||||||||||||
12) <li> <a href=“/movies”>Movies Information</a> </li> |
||||||||||||||||||||
13) <li> <a href=“/sports”>Sports Information</a> </li> |
||||||||||||||||||||
14) <li> <a href=“/politics”>Politics Information</a> </li> |
||||||||||||||||||||
15) </ul> |
||||||||||||||||||||
16) </body> |
||||||||||||||||||||
17) </html> news.html
|
views.py
1) from django .shortcuts import render |
|||||||||||||||||||||||||||||||||||||||||||||
2) |
|||||||||||||||||||||||||||||||||||||||||||||
3) #Create your views here. |
|||||||||||||||||||||||||||||||||||||||||||||
4) def moviesInfo(request): |
|||||||||||||||||||||||||||||||||||||||||||||
5) my_dict={‘head_msg’:‘Movies Information’, |
|||||||||||||||||||||||||||||||||||||||||||||
6) ‘sub_msg1’:‘Christopher slowly getting cured’, |
|||||||||||||||||||||||||||||||||||||||||||||
7) ‘sub_msg2’:‘Bahubali-3 is just planning’, |
|||||||||||||||||||||||||||||||||||||||||||||
8) ‘sub_msg3’:‘Salman Khan ready to marriage’, |
|||||||||||||||||||||||||||||||||||||||||||||
9) ‘photo’:‘images/sunny.jpg’} |
|||||||||||||||||||||||||||||||||||||||||||||
10) return render(request,‘news.html’,context=my_dict) |
|||||||||||||||||||||||||||||||||||||||||||||
11) def sportsInfo(request): |
|||||||||||||||||||||||||||||||||||||||||||||
12) my_dict={‘head_msg’:‘Sports Information’, |
|||||||||||||||||||||||||||||||||||||||||||||
13) ‘sub_msg1’:‘Anushka Sharma Firing Like anything’, |
|||||||||||||||||||||||||||||||||||||||||||||
14) ‘sub_msg2’:‘Kohli updating in game anything can happend’, |
|||||||||||||||||||||||||||||||||||||||||||||
15) ‘sub_msg3’:‘Worst Performance by India-Sehwag’, |
|||||||||||||||||||||||||||||||||||||||||||||
16) } |
|||||||||||||||||||||||||||||||||||||||||||||
17) return render(request,‘news.html’,context=my_dict) |
|||||||||||||||||||||||||||||||||||||||||||||
18) def politicsInfo(request): |
|||||||||||||||||||||||||||||||||||||||||||||
19) my_dict={‘head_msg’:‘Politics Information’, |
|||||||||||||||||||||||||||||||||||||||||||||
20) ‘sub_msg1’:‘Achhce Din Aaa gaya’,
settings.py
|