def current_datetime(request):
now = datetime.datetime.now()
html = "<html><body>It is now %s.</body></html>" % now
return HttpResponse(html)
函数的第二行代码用 Python 的格式化字符串(format-string)功能构造了一段 HTML 响应。 字符串中的%s是占位符,字符串后面的百分号表示用它后面的变量now的值来代替%s。变量%s是一个datetime.datetime对象。它虽然不是一个字符串,但是%s(格式化字符串)会把它转换成字符串,如:2014-11-03 14:15:43.465000。这将导致HTML的输出字符串为:It is now 2014-11-03 14:15:43.465000。
完成添加views.py上述代码之后,同上,在urls.py中添加URL模式,以告诉Django由哪一个URL来处理这个视图。 如下:我们定义/mytime/URL:
from django.conf.urls import patterns, include, url
from mysite.views import hello,current_datetime
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()