視圖是一個網(wǎng)頁“類型”在Django應(yīng)用程序,提供特定的功能,并且具有特定的模板。例如,在一個博客的應(yīng)用程序,可能有以下幾個視圖:
博客首頁 - 顯示最后的幾個文章。 進入“detail”頁面- 對單個項目永久鏈接頁面。 存檔頁 - 顯示所有在給定年份各月的條目。 月存檔頁 - 顯示所有給定月份各天的所有項。 天存檔頁 - 顯示某一天所有條目。 評論操作 - 處理發(fā)布評論的一個給定輸入。
在我們的 poll 應(yīng)用程序,有以下四個視圖:
問題的“index”頁- 顯示最后幾個問題。 問題的“detail”頁 - 顯示一個問題文本,沒有結(jié)果但有一個表單用來投票。 問題的“results”頁面 - 顯示結(jié)果一個特定問題。 投票操作 - 處理投票在一個特定的問題進行具體選擇。
在Django中,網(wǎng)頁和其他內(nèi)容由視圖提供。每個視圖由一個簡單的Python函數(shù)來表示(或方法,基于類的視圖)。Django會選擇一個視圖通過考察多數(shù)民眾贊成請求的URL(準確地說,在域名之后URL的一部分)。
一個URL模式是一個簡單的URL的一般形式 - 例如:/newsarchive/<year>/<month>/.
現(xiàn)在,讓我們添加一些視圖在 polls/views.py。這些視圖略有不同,因為他們需要一個參數(shù):
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 模塊中如下的 url() 調(diào)用,polls/urls.py文件中的代碼如下:
from django.conf.urls import url 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'), ]
您可以在瀏覽器打開“/polls/34/”。它會運行detail()方法,并顯示任何提供的URL內(nèi)容。 再次嘗試訪問 “/polls/34/results/” and “/polls/34/vote/” – 這將顯示占位符結(jié)果和投票頁面。
include() 可以很容易包含入插件和網(wǎng)址。因為polls是在它們自己的URL配置(polls/urls.py),它們可以放置在“/polls/”,或 “/fun_polls/”,或在“/content/polls/”,或任何其它路徑的根,應(yīng)用程序仍然可以工作。
下面是如果用戶進入“/polls/34/”,在這個系統(tǒng)會發(fā)生什么:
Django會找到匹配'^polls/' 然后,Django會去掉匹配的文本("polls/")
并發(fā)送剩余的文本 – "34/" – 到'polls.urls'URL配置用于進一步處理相匹配 r'^(?P<question_id>[0-9]+)/$'從而調(diào)用detail() 視圖,如下所示:
detail(request=<HttpRequest object>, question_id='34')
question_id='34' 是來自 (?P<question_id>[0-9]+)的一部分,用周圍的模式括號“捕捉”匹配該模式文本,并將其作為參數(shù)傳遞給視圖函數(shù); ?P<question_id> 定義了將被用來識別所述匹配的模式的名稱; 以及[0-9]+ 正則表達式匹配一個數(shù)字序列(在一個數(shù)字)。
由于URL模式是正則表達式,可以使用它來做一些事情,沒有任何限制。而且也沒有必要添加URL為.html – 除非你想,在這種情況下,你可以這樣做:
url(r'^polls/latest\.html$', views.index),
每個視圖負責做兩件事情之一:返回包含所請求的頁面內(nèi)容的 HttpResponse 對象,或拋出一個異常,如HTTP 404。 修改polls/views.py文件代碼如下:
from django.http import HttpResponse from .models import Question def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] output = ', '.join([q.question_text for q in latest_question_list]) return HttpResponse(output) # Leave the rest of the views (detail, results, vote) unchanged
在這里有一個問題就,通過:網(wǎng)頁設(shè)計是硬編碼在視圖中。如果想改變頁面的樣子,必須編輯這個 Python 代碼。因此,讓我們使用 Django 模板系統(tǒng)通過創(chuàng)建視圖可以使用模板來分開Python 的代碼。polls/templates/polls/index.html 將下面的代碼:
{% if latest_question_list %} <ul> {% for question in latest_question_list %} <li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li> {% endfor %} </ul> {% else %} <p>No polls are available.</p> {% endif %}
現(xiàn)在我們來更新首頁視圖 polls/views.py使用以下模板(代碼):
from django.http import HttpResponse from django.template import loader from .models import Question def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] template = loader.get_template('polls/index.html') context = { 'latest_question_list': latest_question_list, } return HttpResponse(template.render(context, request))
該代碼加載模板調(diào)用polls/index.html,然后傳遞給它的上下文。上下文是一個字典以Python對象映射模板變量名?,F(xiàn)在訪問URL(http://127.0.0.1:8000/polls/)查看結(jié)果 :
這是一個非常習慣用法來加載模板,填充上下文中和渲染模板的結(jié)果返回一個HttpResponse對象。Django提供了一個捷徑。下面是完整的index() 視圖,改寫polls/views.py為:
from django.shortcuts import render from .models import Question def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] context = {'latest_question_list': latest_question_list} return render(request, 'polls/index.html', context)
請注意,當在各個視圖做到了這一點,我們不再需要導(dǎo)入加載器和HttpResponse對象(想保留HttpResponse,如果仍然有短截 detail, results, 和 vote 方法。
現(xiàn)在,讓我們來解決這個問題詳細視圖 - 顯示為給定的民意調(diào)查問題文本的頁面。這里添加視圖代碼(polls/views.py):
from django.http import Http404 from django.shortcuts import render from .models import Question # ... def detail(request, question_id): try: question = Question.objects.get(pk=question_id) except Question.DoesNotExist: raise Http404("Question does not exist") return render(request, 'polls/detail.html', {'question': question})
注意這里:視圖引發(fā)HTTP404異常,如果與請求ID的問題并不存在。
我們將討論可以把 polls/detail.html 在后面做一些修改,但如果想快速使用上面的實例,polls/templates/polls/detail.html 文件只需包含:
{{question}}
引發(fā) 404 錯誤,現(xiàn)在我們請求一個不存在問題,如:http://127.0.0.1:8000/polls/100/,顯示結(jié)果如下:
如果對象不存在的一個非常習慣用法使用get()并引發(fā)HTTP404錯誤。Django提供了一個捷徑。下面是 detail() 視圖,polls/views.py 改寫:
from django.shortcuts import get_object_or_404, render from .models import Question # ... def detail(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/detail.html', {'question': question})
get_object_or_404()函數(shù)接受一個Django模型作為第一個參數(shù)和關(guān)鍵字任意參數(shù)數(shù)量,它傳遞到模型管理的 get()函數(shù)。
如果對象不存在將引發(fā)HTTP404。
還有一個get_list_or_404()函數(shù),它的工作原理就像get_object_or_404()- 除了使用 filter()而不是get()方法。如果列表是空的它會引起HTTP404。
回到我們的 polls 應(yīng)用程序 detail() 視圖。由于上下文變量的問題,這里的 polls/detail.html 模板看起來是這樣的:
<h1>{{ question.question_text }}</h1> <ul> {% for choice in question.choice_set.all %} <li>{{ choice.choice_text }}</li> {% endfor %} </ul>
模板系統(tǒng)采用點查詢語法來訪問變量屬性。在這個實例 {{question.question_text }},第一個Django確實在question對象字典查找。 如果找不到,它再嘗試屬性查詢 – 如果屬性查找失敗,它會嘗試一個列表索引查找。
現(xiàn)在測試我們上面編寫的代碼,在瀏覽器中打開:http://127.0.0.1:8000/polls/5/ 得到結(jié)果如下:
請記住,當我們在 polls/index.html 鏈接到一個問題,鏈接被硬編碼的部分是這樣的:
<li><ahref="/polls/{{question.id}}/">{{question.question_text}}</a></li>
使用此硬編碼,緊密耦合的方法的問題是:它在更改項目的URL用了很多模板。不過,既然 polls.urls模塊中定義名稱參數(shù)url() 函數(shù),您可以通過使用 {% url %}模板刪除標簽在URL配置中定義的特定URL路徑的依賴:
<li><ahref="{%url'detail'question.id%}">{{question.question_text}}</a></li>
這種工作方式是通過為polls.urls模塊中指定查找的URL定義??梢詼蚀_地看到'detail'的URL名稱定義如下:
... # the 'name' value as called by the {% url %} template tag url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail'), ...
如果你想要把投票詳細視圖的URL更改成其它的,也許像 polls/specifics/12/ 取代在模板(或templates),需要在 polls/urls.py 改變它:
... # added the word 'specifics' url(r'^specifics/(?P<question_id>[0-9]+)/$', views.detail, name='detail'), ...
本教程項目只有一個應(yīng)用程序 - polls。在實際的Django項目中,可能有五個,十個,二十個或更多的應(yīng)用程序。Django 如何區(qū)分它們的URL的名稱? 例如,投票應(yīng)用程序有一個詳細視圖,因此可能會在一個博客的同一個項目也有相同的應(yīng)用程序。如何使用 {% url %} 模板標簽讓Django知道創(chuàng)建一個URL哪些應(yīng)用有這樣視圖?
答案就是將命名空間添加到URLconf。在polls/urls.py文件,繼續(xù)前進,添加應(yīng)用程序名稱設(shè)置應(yīng)用程序命名空間,打開 polls/urls.py:
from django.conf.urls import url from . import views app_name = 'polls' urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail'), url(r'^(?P<question_id>[0-9]+)/results/$', views.results, name='results'), url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'), ]
現(xiàn)在修改 polls/index.html 模板,打開 polls/templates/polls/index.html 文件添加以下代碼:
<li><ahref="{%url'detail'question.id%}">{{question.question_text}}</a></li>
使其指向在命名空間 detail 視圖,打開 polls/templates/polls/index.html 文件如下:
<li><ahref="{%url'polls:detail'question.id%}">{{question.question_text}}</a></li>