20121023 django学习笔记3

设计url

mysite/urls.py

 1 from django.conf.urls import *
 2 
 3 # Uncomment the next two lines to enable the admin:
 4 from django.contrib import admin
 5 admin.autodiscover()
 6 
 7 urlpatterns = patterns('',
 8     url(r'^polls/', include('polls.urls')),
 9     url(r'^admin/', include(admin.site.urls)),
10 )

polls/urls.py

1 from django.conf.urls import *
2 
3 urlpatterns = patterns('polls.views',
4     url(r'^$', 'index',),
5     url(r'^(?P<poll_id>\d+)/$', 'detail',),
6     url(r'^(?P<poll_id>\d+)/results/$', 'results',),
7     url(r'^(?P<poll_id>\d+)/vote/$', 'vote',),
8 )

通过正则表达式匹配对应的url以调用相应的视图

视图polls/views.py

 1 from django.template import Context, loader
 2 from polls.models import Poll
 3 from django.http import HttpResponse
 4 from django.shortcuts import render_to_response, get_object_or_404
 5 from django.http import Http404
 6 
 7 def index(request):
 8     latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
 9     return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
10 
11 def detail(request, poll_id):
12     p = get_object_or_404(Poll, pk=poll_id)
13     return render_to_response('polls/detail.html', {'poll': p})
14 
15 def results(request, poll_id):
16     return HttpResponse("You're looking at the results of poll %s." % poll_id)
17 
18 def vote(results, poll_id):
19     return HttpResponse("You're voting on poll %s." % poll_id)

视图函数中polls/index.html为模板

模板路径的定义在settings.py中TMPLATE_DIRS

 

模板polls/index.html

1 {% if latest_poll_list %}
2     <ul>
3     {% for poll in latest_poll_list %}
4         <li><a href="/polls/{{poll.id}}/">{{poll.question}}</a></li>
5     {% endfor %}
6     </ul>
7 {% else %}
8     <p>No polls are available.</p>
9 {% endif %}
posted @ 2012-10-23 12:40  zhu327  阅读(269)  评论(0)    收藏  举报