繼續(xù)折騰官方文檔教程上的投票應(yīng)用,這回主要是講如何創(chuàng)建django的視圖(views)。
view是django應(yīng)用中網(wǎng)頁(yè)的一種類(lèi)型,每個(gè)view有一個(gè)特定的模板,服務(wù)于一個(gè)特定的方法。
投票系統(tǒng)這個(gè)應(yīng)用比較簡(jiǎn)潔,主要有以下4個(gè)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.
如何從一個(gè)url訪問(wèn)其對(duì)應(yīng)的view,與URLconf有關(guān)。
1、寫(xiě)第一個(gè)view
修改“
polls/views.py”文件,輸出hello world。
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello, world. poll index.");
修改poll應(yīng)用的url文件("
polls/urls.py"):
from django.conf.urls import patterns, url
from polls import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
)
修改項(xiàng)目的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)),
)
從上述代碼可以看出,視圖通過(guò)HttpResponse對(duì)象來(lái)顯示頁(yè)面。http訪問(wèn)時(shí),url則是先通過(guò)項(xiàng)目的url文件("mysite/urls.py")正則表達(dá)式匹配過(guò)濾,再到具體應(yīng)用的urls文件匹配視圖。
url()方法參數(shù):regex,view,kwargs,name
regex 正則表達(dá)式匹配url鏈接(不含參數(shù))。例如訪問(wèn)“
http://www.example.com/myapp/?page=3
”,url鏈接部分為“myapp/”;
view 視圖。url訪問(wèn)時(shí),Django匹配到對(duì)應(yīng)的url鏈接,則會(huì)調(diào)用其對(duì)應(yīng)的view方法;
kwargs 傳遞給目標(biāo)view的參數(shù);
name 給url命名,以便于識(shí)別;
2、寫(xiě)多個(gè)views
請(qǐng)求的url根據(jù)正則表達(dá)式匹配對(duì)應(yīng)的視圖。
修改poll應(yīng)用的views文件("
polls/views.py"):
index演示了查詢最近5條poll記錄,并把poll的question以逗號(hào)連接返回到頁(yè)面。
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應(yīng)用的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、使用模板來(lái)展示頁(yè)面
為了提高效率,使用模板功能來(lái)定義html頁(yè)面布局。
創(chuàng)建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的標(biāo)記語(yǔ)言。views中會(huì)載入模板渲染,填充數(shù)據(jù)到標(biāo)記,生成最終的web頁(yè)面返回。
修改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))
方法簡(jiǎn)化:render()
這是個(gè)可以簡(jiǎn)化views中生成頁(yè)面的API,讓代碼更簡(jiǎn)潔一點(diǎn)。
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請(qǐng)求時(shí),返回一個(gè)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})
創(chuàng)建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>
方法簡(jiǎn)化:get_object_or_404()
使用該API簡(jiǎn)化模型與視圖的耦合度。
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硬編碼,如果以后項(xiàng)目polls鏈接發(fā)生變動(dòng),則模板也要一起修改。
<li><a href="/polls/{{ poll.id }}/">{{ poll.question }}</a></li>
使用模板語(yǔ)言的{% url %}標(biāo)記可以消除這種問(wèn)題。
<li><a href="{% url 'detail' poll.id %}">{{ poll.question }}</a></li>
通過(guò)url標(biāo)記,來(lái)調(diào)用urls.py("polls/urls.py")配置文件中取名為detail的url鏈接。
url(r'^(?P<poll_id>\d+)/$', views.detail, name='detail'),
如果url有所變動(dòng),例如在原有基礎(chǔ)上增加(“polls/specifics/12/”)
url(r'^specifics/(?P<poll_id>\d+)/$', views.detail, name='detail'),
6、URL命名空間
項(xiàng)目存在多個(gè)應(yīng)用時(shí),不同應(yīng)用之間url名字可能存在重復(fù)。給每個(gè)應(yīng)用加上命名空間以避免命名沖突問(wèn)題。
給項(xiàng)目的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調(diào)用url標(biāo)記時(shí),加上命名空間前綴。
<li><a href="{% url 'polls:detail' poll.id %}">{{ poll.question }}</a></li>