Natural

           

          Django官方文檔學(xué)習(xí)筆記:Tutorial: Part 3

              繼續(xù)折騰官方文檔教程上的投票應(yīng)用,這回主要是講如何創(chuàng)建django的視圖(views)。
              view是django應(yīng)用中網(wǎng)頁的一種類型,每個view有一個特定的模板,服務(wù)于一個特定的方法。
             
              投票系統(tǒng)這個應(yīng)用比較簡潔,主要有以下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訪問其對應(yīng)的view,與URLconf有關(guān)。

              1、寫第一個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'),
          )
              修改項目的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")正則表達(dá)式匹配過濾,再到具體應(yīng)用的urls文件匹配視圖。
             
              url()方法參數(shù):regex,view,kwargs,name
              regex      正則表達(dá)式匹配url鏈接(不含參數(shù))。例如訪問“
          http://www.example.com/myapp/?page=3
          ”,url鏈接部分為“myapp/”;
              view        視圖。url訪問時,Django匹配到對應(yīng)的url鏈接,則會調(diào)用其對應(yīng)的view方法;
              kwargs    傳遞給目標(biāo)view的參數(shù);
              name       給url命名,以便于識別;

              2、寫多個views
              請求的url根據(jù)正則表達(dá)式匹配對應(yīng)的視圖。
              修改poll應(yīng)用的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應(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、使用模板來展示頁面

          為了提高效率,使用模板功能來定義html頁面布局。

          創(chuàng)建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的標(biāo)記語言。views中會載入模板渲染,填充數(shù)據(jù)到標(biāo)記,生成最終的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})

           

          創(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>

             

              方法簡化: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鏈接發(fā)生變動,則模板也要一起修改。

          <li><href="/polls/{{ poll.id }}/">{{ poll.question }}</a></li>

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

          <li><href="{% url 'detail' poll.id %}">{{ poll.question }}</a></li>

              通過url標(biāo)記,來調(diào)用urls.py("polls/urls.py")配置文件中取名為detail的url鏈接。

          url(r'^(?P<poll_id>\d+)/$', views.detail, name='detail'),

              如果url有所變動,例如在原有基礎(chǔ)上增加(“polls/specifics/12/

          url(r'^specifics/(?P<poll_id>\d+)/$', views.detail, name='detail'),


              6、URL命名空間

              項目存在多個應(yīng)用時,不同應(yīng)用之間url名字可能存在重復(fù)。給每個應(yī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)記時,加上命名空間前綴。

          <li><href="{% url 'polls:detail' poll.id %}">{{ poll.question }}</a></li>




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

          導(dǎo)航

          統(tǒng)計

          常用鏈接

          留言簿(8)

          隨筆分類(83)

          隨筆檔案(78)

          文章檔案(2)

          相冊

          收藏夾(7)

          最新隨筆

          搜索

          積分與排名

          最新評論

          閱讀排行榜

          評論排行榜

          主站蜘蛛池模板: 新巴尔虎左旗| 女性| 漠河县| 镇江市| 康乐县| 无极县| 仙游县| 肇庆市| 和静县| 思茅市| 富平县| 铜鼓县| 昌邑市| 漾濞| 泸水县| 信丰县| 偏关县| 尼玛县| 湛江市| 平遥县| 个旧市| 无锡市| 赫章县| 巴林右旗| 西充县| 裕民县| 松阳县| 滨州市| 九寨沟县| 石嘴山市| 怀来县| 泌阳县| 海丰县| 绥江县| 林周县| 正阳县| 普陀区| 温泉县| 区。| 耒阳市| 明溪县|