Why we need template on Django ?

Let's create a simple website by django ...

step01:

django-admin startproject x01

step02:

cd x01
ls

You will see ...

or you can use tree:

tree

 

step03:

write the first view for your website ...

cd x01
vim views.py

write the below code into your new file ( views.py 

from django.http import HttpResponse

def hello(request):
    return HttpResponse("Hello World")

 

step04:

Let the django know you have a new view,so add the url to urls.py

vim urls.py

You will see something like below ..

 

step05

delete all ...

and then write the below code into the ( urls.py )

from django.conf.urls import patterns
from x01.views import hello

urlpatterns = patterns('',
        ('^hello/$,hello),
)

 

After input ,You will got something like the below ..

 

step06:

python manage.py runserver

You will see the below ...

 

step07:

check and see if you can visit ...

 

If you see this,mean you have success ..

Congratulation ...

 

step08:

Why we need the template ...?

see the second example,just change your (views.py) like the below ...

 

and then change the (urls.py ) like below ..

 

and then visit your website again ..

 

And ,you must think,it's so boring to write the 'html inline python' ...

so the template is work for you ...

 

step09:

 

 

and change your (urls.py)

like the below show ...

 

run and check again ..

 

If you see the result ,you are success again ...

 

step10:

 

But we can see,the both python and html still in the same file ( views.py ) ...

We want do samething let it at different file (template.html ) and (views.py) ...

 create a templates dir ..

mkdir templates

 

and then let the django you have new (templates)

cd x01
vim setting.py

You will see:

 

I have already add the (template ) see line58 ...

and then modify our (views.py )

 

okay, let's check our website ...

 

we got a Exception ...

Because,we haven't write our template file name as ( current_datetime.html )

let's do it  ..

 

and check again ...

 

step11:

Let's see our views.py ,

 

The line1,2,3 is so boring,Is there any way can change this situation ..

get_template + Context +HttpResponse = ??

The answer is True ...

Modify the views.py like below code ...

 

and then,check your website ...

 

If you see the time ...you have success again ...

 

step12:

Keep let it easy ...

(use locals() instead more temp variable ...)

 

step13:

 

posted @ 2015-07-07 11:19  Landpack  阅读(255)  评论(0编辑  收藏  举报