环境: python 2.7 32位,Django1.6.7,win7 64位系统
承接前2篇文章
模板加载
在mysite下新建一个templates文件夹,然后在setting.py添加以下内容:
import os.path TEMPLATE_DIRS = ( os.path.join(os.path.dirname(__file__), 'templates').replace('\\','/'), )
模板编写
urls.py
from django.conf.urls import patterns, include, url from mysite.views import hello from books.views import current_datetime from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'mysite.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^hello/$', hello), url(r'^current_datetime/$',current_datetime), )
current_datetime.html
<html><body>It is now {{ current_date }}.</body></html>
views.py
from django.shortcuts import render from django.template import Context from django.template.loader import get_template from django.http import HttpResponse import datetime # Create your views here. def current_datetime(request): now = datetime.datetime.now() t = get_template('current_datetime.html') html = t.render(Context({'current_date':now})) return HttpResponse(html)
def current_datetime(request): current_date = datetime.datetime.now() return render_to_response('current_datetime.html', locals())
运行python manage runserver
在浏览器输入http://127.0.0.1:8000/current_datetime/,即可看到网页 输出当前的时间
base.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="en"> <head> <title>{% block title %}{% endblock %}</title> </head> <body> <h1>My helpful timestamp site</h1> {% block content %}{% endblock %} {% block footer %} <hr> <p>Thanks for visiting my site.</p> {% endblock %} </body> </html>
{% extends "base.html" %} {% block title %}The current time{% endblock %} {% block content %} <p>It is now {{ current_date }}.</p> {% endblock %}