视图简介
Django遵循MVC设计模式,视图可以对请求做出响应。每个视图由一个函数表示。
Django通过URL来选择调用那个视图。
第一个视图
创建视图函数
打开polls/views.py文件并将以下Python代码写入:
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def index(request):
return HttpResponse('MTbaby的博客')
配置url
在polls目录中创建一个名为urls.py的文件。输入如下代码:
from django.conf.urls import url
from django.contrib import admin
from . import views
# urlpatterns = [
# url(r'^admin/', admin.site.urls),
# ]
urlpatterns = [
url(r'^$', views.index,name='index'),
]
添加到项目urls
打开myblog目录下面的urls.py,修改如下:
from django.conf.urls import url
from django.contrib import admin
#from . import views
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^polls/',include('polls.urls')),
]
这里使用正则表达式,如果你还不太熟悉正则表达式,可以看看我们的Python基础课程正则表达式的内容:
访问
启动项目python manage.py runserver
打开浏览器输入:http://127.0.0.1:8000/polls/ 结果如下:
MTbaby的博客
编写更多的视图
现在让我们给polls/views.py添加一些更多的视图。这些视图和之前的略有不同,因为它们另带了一个参数:
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def index(request):
return HttpResponse('MTbaby的博客')
def detail(request,question_id):
return HttpResponse('你正在浏览的页数:%s'%question_id)
def result(request,question_id):
response = "你正在浏览页数%s的结果"
return HttpResponse(response % question_id)
def vote(request,question_id):
return HttpResponse("你正在为%s投票" % question_id)
通过下面的url() 调用将这些新的视图和polls.urls模块关联起来:
from django.conf.urls import url
from django.contrib import admin
from . import views
# urlpatterns = [
# url(r'^admin/', admin.site.urls),
# ]
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://127.0.0.1:8000/polls/ :MTbaby的博客
http://127.0.0.1:8000/polls/1/ : 你正在浏览的页数: 1.
http://127.0.0.1:8000/polls/1/results/ : 正在浏览页数1的结果
http://127.0.0.1:8000/polls/1/vote/ : 你正在为1投票