概述:
视图(view)是Django应用中的一类网页, 它通常使用一个特定的函数提供服务,并且具有一个特定的模板。
写更多视图
现在让我们给polls/views.py添加一些更多的视图。 这些视图和之前的略有不同,因为它们另带了一个参数:
polls/views.py
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)
通过下面的url() 调用将这些新的视图和polls.urls模块关联起来:
from . import views
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'),
]
看看你的浏览器,输入"/34/"它将运行detail()方法并显示你在URL中提供的ID。
当有人从你的网站请求一个页面 --例如 "/polls/34/"时,Django 将加载mysites.urls Python模块
在'^polls/' 找到匹配后,它将取消匹配的文件("polls/"),并发送剩余的文本 - "34/" 到polls.urls's URLconf进行进一步处理。
它匹配'^(?P<question_id>[0-9]+)/$',导致调用detail()视图
http://192.168.137.2:9000/polls/34/
polls/views.py
def detail(request, question_id):
return HttpResponse("You're looking at question %s." % question_id)
urlpatterns = [
url(r'^polls/', include('polls.urls')),
url(r'^admin/', admin.site.urls),
]
# ex: /polls/5/
url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail'),