標籤:
前面已經說過了Django中model的一些用法,包括orm,以及操作的api,接下來就是搭一些簡單的介面學習view——Django中的view。主要介紹以下兩個方面:
url映射和請求處理共同構成了MVC中的C——controller,這裡面涉及了url的寫法(主要是Regex),接收頁面傳遞過來的參數。在Django中可以使用template來進行頁面渲染,這樣可以直接使用傳遞過來的資料。
url映射
這裡緊接著上一篇的工程完善polls項目,polls網站首頁顯示最近的問題列表,還可以查看某一個問題的詳情,可以進一步查看調查問題的結果。進行投票
- index:顯示最近的問題列表
- detail:查看調查問題詳細資料
- result:顯示某一個問題的結果
- vote:對問題某一個答案進行投票
以上的四個功能我們分別用四個頁面,編輯polls/urls,py
from django.conf.urls import urlfrom . import viewsapp_name = ‘polls‘urlpatterns = [ url(r‘^$‘, views.index, name = ‘index‘), url(r‘^(?P<question_id>[0-9]+)/detail/$‘, 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‘),]
name:url規則的名稱,可在模板中引用
app_name:定義url的命名空間,命名空間的作用就是防止name重名
請求處理
編輯polls/views.py
from django.shortcuts import render, get_object_or_404from django.http import HttpResponse, Http404from models import Question# Create your views here.def index(request):
# 查詢最新的五條Question,- 表示降序排列 latest_question_list = Question.objects.order_by(‘-publ_date‘)[:5] context = {‘latest_question_list‘: latest_question_list} return render(request, ‘polls/index.html‘, context)def detail(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, ‘polls/detail.html‘, {‘question‘: question})def results(request, question_id): return HttpResponse("result:question id is %s" % question_id)def vote(request, question_id): return HttpResponse("vote:question id is %s" % question_id)
views.py處理通過urls.py分發過來的請求,比如上面最後一個vote中,很簡單直接返回一個HttpResponse對象,其實所有的views處理都是返回該HttpResponse對象,包括使用能夠render方法的時候
- 直接返回HttpResonse
- 通過調用render,將資料渲染到templates再返回HttpResponse
get_object_or_404:擷取一個Question對象,如果沒有就拋出Http404 Exception,這是經過最佳化後的代碼,本來是自己手動尋找一個對象,自己判斷對象是否存在,不存在再raise Exception,改進之後降低了model和view之間的耦合,這樣view不再依賴model層的具體實現,達到解耦的目的。
模板檔案
在mysite/polls下建立兩級目錄mysite/polls/templates/polls,templates是固定的,polls是APP名稱,然後在mysite/polls/templates/polls目錄下建立一個index.html檔案——也就是模板檔案
{% if latest_question_list %} <ul> {% for question in latest_question_list %} <li><a href="{% url ‘polls.detail‘ question.id %}">{{ question.question_text }}</a></li> {% endfor %} </ul>{% else %} <p>No polls are available.</p>{% endif %}
這裡有幾點先說明一下:
templates/polls目錄
在settings.py裡面有關於templates的配置
TEMPLATES = [ { ‘BACKEND‘: ‘django.template.backends.django.DjangoTemplates‘, ‘DIRS‘: [], ‘APP_DIRS‘: True, ‘OPTIONS‘: { ‘context_processors‘: [ ‘django.template.context_processors.debug‘, ‘django.template.context_processors.request‘, ‘django.contrib.auth.context_processors.auth‘, ‘django.contrib.messages.context_processors.messages‘, ], }, },]
BACKEND:後端用的模板引擎django.template.backends.django.DjangoTemplates
DIRS:模板的位置也就是說不一定要放在約定的目錄裡面,但是建議最好放在每個APP名稱的目錄下,避免多個APP的情況下有模板名稱相同的時候Django分不清
APP_DIRS:為true的時候DjangoTemplates會搜尋app所在目錄下的模板即polls/templates/polls
所以上面我們放在了預設目錄
template文法
在Djang的模板裡麵包含普通的html代碼和模板代碼,比如if-else,for,dotted文法(訪問資料)等。這裡先介紹一些基本的,關於html不多說。
- 模板代碼使用普通{%%}包圍,還有比如{%url%}文法
- {{模板中的資料}}
- {%if %} {%else %} {%endif %}
- {%for %} {%endfor%}
- latest_question_list為views.py傳遞過來的參數,可以使用點文法訪問資料,支援的資料格式有值傳遞和引用(包括:list,dic,tuple,對象屬性,對象方法(沒有其他參數,必須有傳回值)),使用點文法的時候Django搜尋參數的順序是:字典,對象屬性,對象方法,list
url命名空間
<li><a href="{% url ‘polls.detail‘ question.id %}">{{ question.question_text }}</a></li>
在urls.py檔案中通過申明一個全域變數app_name就是url的命名空間,在{%url %}文法中就可以使用app_name+name 的方式引用url,比如‘polls.detail’說明使用哪一個url匹配,question_id為傳遞給url匹配的參數
總結
除了學習Django的基本知識,還學習(膜拜)了Django的精巧設計,松耦合
- Django對擷取單個對象的時候Http404異常做了封裝,解耦model和view
- 使用{%url %}文法不需要將url寫入程式碼在template檔案中,達到和url映射解耦的目的
完整代碼
http://pan.baidu.com/s/1kUFv5lH
frist Django app — 三、 View