from django.conf.urls import patterns, include, urlfrom mysite.views import hello,index,test,home,edit #引入视图文件mysite/mysite/views.py urlpatterns = patterns('',#正则路由 url(r'^$',home), url(r'^hello/index$', index), url(r'^hello/hello$', hello), url(r'^hello/test$', test), url(r'^hello/edit/\d+$',edit),)
我们建了几个路由,指向了mysite/mysite/views.py 文件的几个方法(hello,index,test,home,edit),我们进去建这几个方法
from django.http import HttpResponsefrom django.shortcuts import render_to_responseimport datetimeclass myclass(object): def __init__(self,name,age,sex): self.name = name self.age = age self.sex = sexdef hello(request): return HttpResponse('hello world')def index(request): return HttpResponse('Hello world index')def home(request): now = datetime.datetime.now() html = "%s.
" % now return HttpResponse(html)def edit(request): return HttpResponse("id is 12")def test(request): mylist = ["one","two",3,4] mymap = {'name':'tongjh','age':22,'sex':'nan'} my_class = myclass('zhangsan',25,'nv') return render_to_response('index.html',{'title':'title','mylist':mylist,'mymap':mymap,'myclass':myclass})
我们看到test方法中使用了模板 return render_to_response('index.html',{'title':'title','mylist':mylist,'mymap':mymap,'myclass':myclass}) 这里是指使用templates下的index.html,我上篇博客安装篇中有介绍配置template的位置,第二个参数是分配变量,我分配了 list,map,class和普通变量,看看模板中是怎么解析的
打开mysite/mysite/templates/index.html文件
{ {title}}
- { {mylist.0}}
- { {mylist.1}}
- { {mylist.2}}
- { {mylist.3}}
name : { {mymap.name}},age:{ {mymap.age}},sex:{ {mymap.sex}}
myclass : { {my_class.name}}--{ {my_class.age}}--{ {my_class.sex}}
{% if mymap%} ok { {mymap.name}} {% else %} not mymap {% endif %}
{% for my in mylist %} { { forloop.counter }}: { {my}} {% endfor %}
{% for k,v in mymap.items %} { {k}} : { {v}} {% endfor %}
关于django大象哥推荐大家看这个中文文档,http://djangobook.py3k.cn/2.0/