1. Template(views.py
2. urls.py
views.py
templates/current_time.html
settings.py
3. 继续改进views.py
from django.template import Template, Context
from django.http import HttpResponse
import datetime
def current_datetime(request):
now = datetime.datetime.now()
t = Template("<html><body>It is now {{current_date}}.
</body></html>")
html = t.render(Context({'current_date': now}))
return HttpResponse(html)
2. urls.py
from django.conf.urls.defaults import patterns, include, url
from mysite.views import current_datetime_now
urlpatterns = patterns('',
# set now time now
('^timenow/$', current_datetime_now),
)
views.py
from django.template.loader import get_template
from django.template import Context
from django.http import HttpResponse
import datetime
def current_datetime_now(request):
now = datetime.datetime.now()
t = get_template('current_datetime.html')
html = t.render(Context({'current_date': now}))
return HttpResponse(html)
templates/current_time.html
<html>
<body>
It is now {{ current_date }}.
</body>
</html>
settings.py
import os
TEMPLATE_DIRS = (
#'/home/tony/djcode/mysite/templates',
os.path.join(os.path.dirname(__file__), \
'templates').replace('\\','/'),
)
3. 继续改进views.py
from django.shortcuts import render_to_response
import datetime
def current_datetime_shortcut(request):
now = datetime.datetime.now()
return render_to_response('current_datetime.html', \
{'current_date':now})