Working with Django Templates And Static Files

Django Templates:

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) 

OutputD: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


    TEMPLATES = [

        {

            ‘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>

 

7) Define Function based view inside views.py file
 
     

1) from django .shortcuts import render

2) def wish(request):

3) return render(request,‘testApp/wish.html’)

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

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

1) <!DOCTYPEhtml>

2) <htmllang=“en”dir=“ltr”>

3) <head>

4) <title></title>

5) <style>

6) body{

7) background: green;

8) color:white;

9) }

10) h1{

11) border:10px solid yellow;

12) }

13) </style>

14) </head>

15) <body>

16) <h1>Hello this response from Template File.I will take care everything about pres

entation</h1><hr>

17) <h2>The Server Date and Time is:{{date}}</h2>

18) <ol>

19) <li>Name:{{name}}</li>

20) <li>Rollno:{{rollno}}</li>

21) <li>Marks:{{marks}}</li>

22) </ol>

23)

24) </body>

25) </html>


Application to wish End User based on Time 

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) #h11{

8) color:red;

9) }

10) #h12{

11) color:green;

12) }

13) </style>

14) </head>

15) <body>

16) <h1 id=h11>{{insert_msg}}</h1>

17) <h1 id=h12>Current Date and Time : {{insert_date}}</h1>

18) </body>

19) </html>


views.py

1) from django .shortcuts import render

2) import datetime

3)

4) #Create younviews here.

5) def wish(request):

6) date=datetime.datetime.now()

7) msg=‘Hello Guest !!!! Very Very Good ‘

8) h=int(date.strftime(‘%H’))

9) if h<12:

10) msg +=‘Morning!!!’

11) elif h<16:

12) msg +=‘AfterNoon!!!’

13) elif h<21:

14) msg +=‘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)

Templates Based Applications: 

1. Application to Display Hello World

2. Application To display date and time

(observe 3 ways of providing context dictionary)

3. Application To display date ,time and student information

4. Application to display wish message based on time like Good Morning,Good Evening etc 

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) ]

4) Make sure all paths are correct or not

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

1) <!DOCTYPEhtml>

2) {%load static files %}

3) <html lang=“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>{{head_msg}}</h1>

11) <ul>

12) <li> <h2>{{sub_msg1}}</h2> </li>

13) <li> <h2>{{sub_msg2}}</h2> </li>

14) <li> <h2>{{sub_msg3}}</h2> </li>

15) </ul>

16) <img src=”{% static “images/sunny.jpg” %}” alt=“”>

17) <img src=”{% static “images/guido.jpg” %}” alt=“”>

18) <img src=”{% static “images/divine3.jpg” %}” alt=“”>

19) </body>

20) </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’,

21) ‘sub_msg2’:‘Rupee Value now 1$:70Rs’,

22) ‘sub_msg3’:‘In India Single Paisa Black money No more’,

23) }

24) return render(request,‘news.html’,context=my_dict)

25) def index(request):

26) return render(request,‘index.html’)

settings.py 


1) import os

2)

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

4) TEMPLATES_DIR=os.path.join(BASE_DIR,‘templates’)

5) STATIC_DIR=os.path.join(BASE_DIR,‘static’)

6)

7) INSTALLED_APPS=[

8) ‘django .contrib.admin’,

9) ‘django .contrib .auth’,

10) ‘django.contrib.contenttypes’,

11) ‘django.contrib.sessions’,

12) ‘django.contrib.messages’,

13) ‘django.contrib.staticfiles’,

14) ‘newsApp’

15) ]

16)

17) TEMPLATES = [

18) {

19)

20) ‘DIRS’: [TEMPLATES_DIR,],

21)

22) ],

23) },

24) },
25) ]

26)

27) STATIC_URL = ‘/static/’

28) STATICFILES_DIRS=[

29) STATIC_DIR,

30) ]


urls.py

1) from django .conf .urls import url

2) from django .contrib import admin

3) from news App import views

4) urlpatterns = [

5) url(r‘^admin/’, admin.site.urls),

6) url(r‘^movies/’, views.moviesInfo),

7) url(r‘^sports/’, views.sportsInfo),

8) url(r‘^politics/’, views.politicsInfo),

9) url(r‘^$’, views.index),

10) ]





                                        





 

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *