继续折腾官方文档教程上的投票应用,这回主要是讲如何创建django的视图(views)。
view是django应用中网页的一种类型,每个view有一个特定的模板,服务于一个特定的方法。
投票系统这个应用比较简洁,主要有以下4个views:
- Poll “index” page – displays the latest few polls.
- Poll “detail” page – displays a poll question, with no results but with a form to vote.
- Poll “results” page – displays results for a particular poll.
- Vote action – handles voting for a particular choice in a particular poll.
如何从一个url访问其对应的view,与URLconf有关。
1、写第一个view
修改“
polls/views.py”文件,输出hello world。
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello, world. poll index.");
修改poll应用的url文件("
polls/urls.py"):
from django.conf.urls import patterns, url
from polls import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
)
修改项目的url文件("
mysite/urls.py"):
from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'mysite.views.home', name='home'),
# url(r'^mysite/', include('mysite.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^polls/', include('polls.urls')),
url(r'^admin/', include(admin.site.urls)),
)
从上述代码可以看出,视图通过HttpResponse对象来显示页面。http访问时,url则是先通过项目的url文件("mysite/urls.py")正则表达式匹配过滤,再到具体应用的urls文件匹配视图。
url()方法参数:regex,view,kwargs,name
regex 正则表达式匹配url链接(不含参数)。例如访问“
http://www.example.com/myapp/?page=3
”,url链接部分为“myapp/”;
view 视图。url访问时,Django匹配到对应的url链接,则会调用其对应的view方法;
kwargs 传递给目标view的参数;
name 给url命名,以便于识别;
2、写多个views
请求的url根据正则表达式匹配对应的视图。
修改poll应用的views文件("
polls/views.py"):
index演示了查询最近5条poll记录,并把poll的question以逗号连接返回到页面。
from django.http import HttpResponse
from polls.models import Poll
def index(request):
latest_poll_list = Poll.objects.order_by('-pub_date')[:5]
output = ', '.join([p.question for p in latest_poll_list])
return HttpResponse(output)
def detail(request, poll_id):
return HttpResponse("You're looking at poll %s." % poll_id)
def results(request, poll_id):
return HttpResponse("You're looking at the results of poll %s." % poll_id)
def vote(request, poll_id):
return HttpResponse("You're voting on poll %s." % poll_id)
修改poll应用的url文件("
polls/urls.py"):
from django.conf.urls import patterns, url
from polls import views
urlpatterns = patterns('',
# ex: /polls/
url(r'^$', views.index, name='index'),
# ex: /polls/5/
url(r'^(?P<poll_id>\d+)/$', views.detail, name='detail'),
# ex: /polls/5/results/
url(r'^(?P<poll_id>\d+)/results/$', views.results, name='results'),
# ex: /polls/5/vote/
url(r'^(?P<poll_id>\d+)/vote/$', views.vote, name='vote'),
)
3、使用模板来展示页面
为了提高效率,使用模板功能来定义html页面布局。
创建index模板文件("polls/templates/polls/index.html"):
{% if latest_poll_list %}
<ul>
{% for poll in latest_poll_list %}
<li><a href="/polls/{{ poll.id }}/">{{ poll.question }}</a></li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}
html模板中使用了django的标记语言。views中会载入模板渲染,填充数据到标记,生成最终的web页面返回。
修改views的index方法("polls/views.py"):
from django.http import HttpResponse
from django.template import Context, loader
from polls.models import Poll
def index(request):
latest_poll_list = Poll.objects.order_by('-pub_date')[:5]
template = loader.get_template('polls/index.html')
context = Context({
'latest_poll_list': latest_poll_list,
})
return HttpResponse(template.render(context))
方法简化:render()
这是个可以简化views中生成页面的API,让代码更简洁一点。
from django.shortcuts import render
from polls.models import Poll
def index(request):
latest_poll_list = Poll.objects.order_by('-pub_date')[:5]
context = {'latest_poll_list': latest_poll_list}
return render(request, 'polls/index.html', context)
4、抛出404异常
detail视图找不到匹配poll请求时,返回一个http404异常。
from django.http import Http404
def detail(request, poll_id):
try:
poll = Poll.objects.get(pk=poll_id)
except Poll.DoesNotExist:
raise Http404
return render(request, 'polls/detail.html', {'poll': poll})
创建detail模板文件("polls/templates/polls/detail.html"):
<h1>{{ poll.question }}</h1>
<ul>
{% for choice in poll.choice_set.all %}
<li>{{ choice.choice_text }}</li>
{% endfor %}
</ul>
方法简化:get_object_or_404()
使用该API简化模型与视图的耦合度。
from django.shortcuts import render, get_object_or_404
from polls.models import Poll
def detail(request, poll_id):
poll = get_object_or_404(Poll, pk=poll_id)
return render(request, 'polls/detail.html', {'poll': poll})
5、除掉模板中url的硬编码
前者index模板中存在url硬编码,如果以后项目polls链接发生变动,则模板也要一起修改。
<li><a href="/polls/{{ poll.id }}/">{{ poll.question }}</a></li>
使用模板语言的{% url %}标记可以消除这种问题。
<li><a href="{% url 'detail' poll.id %}">{{ poll.question }}</a></li>
通过url标记,来调用urls.py("polls/urls.py")配置文件中取名为detail的url链接。
url(r'^(?P<poll_id>\d+)/$', views.detail, name='detail'),
如果url有所变动,例如在原有基础上增加(“polls/specifics/12/”)
url(r'^specifics/(?P<poll_id>\d+)/$', views.detail, name='detail'),
6、URL命名空间
项目存在多个应用时,不同应用之间url名字可能存在重复。给每个应用加上命名空间以避免命名冲突问题。
给项目的url配置文件("mysite/urls.py")加上命名空间:
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^polls/', include('polls.urls', namespace="polls")),
url(r'^admin/', include(admin.site.urls)),
)
index.html调用url标记时,加上命名空间前缀。
<li><a href="{% url 'polls:detail' poll.id %}">{{ poll.question }}</a></li>