参考:https://docs.djangoproject.com/en/1.9/intro/tutorial03/
来到的MVC的views。我们的例子polls需要四种页面:
- Question的主页面 —— 显示最近的几个questions
- Question的细节页面 —— 显示Question和choices
- Question的结果页面 —— 显示选择的答案结果
- Action handler —— 处理提交的choice
在django中,页面和内容是通过views展示的。每个views被一个python function/method处理。django会通过url来判断哪个view将被调用。
我们常见的web url格式例如:
ME2/Sites/dirmod.asp?sid=&type=gen&mod=Core+Pages&gid=A6CD4967199A42D9B65B1B。虽然也很好懂,但是django支持更加优美的样式,例如
/newsarchive/<year>/<month>/。
为了把url映射到view,django利用了“URLconfs”机制。以下我们做一些简单的介绍。更多详情参见:https://docs.djangoproject.com/en/1.9/ref/urlresolvers/#module-django.core.urlresolvers。
让我们添加一些function到polls/views.py:
from django.shortcuts import render
from django.http import HttpResponse
def index(request):
return HttpResponse("hello, world! httpresponse")
# Create your views here.
def detail(request, question_id):
return HttpResponse("You're looking at question %s." % question_id)
def results(request, question_id):
response = "You're looking at the results of question %s."
return HttpResponse(response % question_id)
def vote(request, question_id):
return HttpResponse("You're voting on question %s." % question_id)
接下来不要忘记polls/urls.py (还记得polls的index是怎么做的不)
urlpatterns = [
# ex: /polls/
url(r'^$', views.index, name='index'),
# ex: /polls/5/
url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail'),
# ex: /polls/5/results/
url(r'^(?P<question_id>[0-9]+)/results/$', views.results, name='results'),
# ex: /polls/5/vote/
url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'),
]
下面让我们来访问一下 http://localhost:8000/polls/1/ :
根据urlpatterns,他会调用detail()方法,把1作为question_id参数。同理,/polls/1/results和/polls/1/vote将会展示results和vote页面。
在我们之前的教程中,mysite/urls.py里已经对r'^polls/'进行了处理,django会自动把请求url中的/polls/之前的部分去掉,后面放到polls/urls.py进行匹配。
可以注意到匹配格式:
(?P<question_id>[0-9]+)中,小括号表明了要获取并保存此部分的内容,
?P<question_id>
定义了保存到的参数名字,而
[0-9]+
就是标准正则表达式的部分了。
显然,由于正则表达式的强大, 你可以对url的view进行任意定义。例如如果你一定需要".html"作为后缀(纯为了好看吗),你可以定义
url(r'^polls/latest\.html$', views.index)
当然,最好不要这么做,因为的确很傻。