Natural

           

          Django官方文檔學習筆記:Tutorial: Part 3

              繼續折騰官方文檔教程上的投票應用,這回主要是講如何創建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><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><href="/polls/{{ poll.id }}/">{{ poll.question }}</a></li>

               使用模板語言的{% url %}標記可以消除這種問題。

          <li><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><href="{% url 'polls:detail' poll.id %}">{{ poll.question }}</a></li>




          posted on 2013-05-10 15:36 此號已被刪 閱讀(1123) 評論(0)  編輯  收藏 所屬分類: Python

          導航

          統計

          常用鏈接

          留言簿(8)

          隨筆分類(83)

          隨筆檔案(78)

          文章檔案(2)

          相冊

          收藏夾(7)

          最新隨筆

          搜索

          積分與排名

          最新評論

          閱讀排行榜

          評論排行榜

          主站蜘蛛池模板: 公安县| 岳池县| 马关县| 阳山县| 西城区| 麻江县| 平山县| 准格尔旗| 招远市| 泰宁县| 平武县| 高州市| 洛南县| 澜沧| 凭祥市| 桐梓县| 黑龙江省| 滨州市| 从化市| 延津县| 莫力| 行唐县| 江阴市| 永城市| 福鼎市| 秦安县| 射阳县| 武汉市| 防城港市| 巴东县| 长寿区| 塘沽区| 滦平县| 宜兰市| 嵊泗县| 茌平县| 屏边| 林州市| 交口县| 博乐市| 垣曲县|