今回は完成形を見た方が早いので以下にまとめました。
流れとしては
polls/views.pyにレスポンスを返すメソッドを指定
mysite/urls.py, polls/urls.pyでURLをマッピング
必要に応じてpolls/templates/以下のテンプレートを利用してレンダリング
って感じ。
mysite/urls.py
from django.conf.urls import patterns, include, url
from polls import views
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
#polls/* のURLの時はpolls/urls.pyを読み込み
url(r'^polls/', include('polls.urls', namespace="polls")),
#管理画面URL設定
url(r'^admin/', include(admin.site.urls)),
)
polls/urls.py
from django.conf.urls import patterns, url
from polls import views
urlpatterns = patterns('',
# ex: /
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'),
)
polls/views.py
from django.http import HttpResponse
from django.template import RequestContext, loader
from django.shortcuts import render, get_object_or_404
from polls.models import Poll
def index(request):
#pub_dateが最新のPollオブジェクトを取得
latest_poll_list = Poll.objects.order_by('-pub_date')[:5]
#ショートカットを使わない場合
"""
template = loader.get_template('polls/index.html')
context = RequestContext(request, {
'latest_poll_list' : latest_poll_list,
})
return HttpResponse(template.render(context))
"""
#テンプレートにバインディングして表示
context = {
'latest_poll_list' : latest_poll_list,
}
return render(request, 'polls/index.html', context)
def detail(request, poll_id):
#主キーからオブジェクトを取得。見つからない場合は404を返す
poll = get_object_or_404(Poll, pk=poll_id)
return render(request, 'polls/detail.html', {'poll':poll})
def results(request, poll_id):
return HttpResponse("result %s" % poll_id)
def vote(request, poll_id):
return HttpResponse("vote %s" % poll_id)
polls/templates/polls/index.html
{% if latest_poll_list %}
<ul>
{% for poll in latest_poll_list %}
<li><a href="{% url 'polls:detail' poll.id %}">{{ poll.question }}</a></li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}
polls/templates/polls/index.html
<h1>{{ poll.question }}</h1>
<ul>
{% for choice in poll.choice_set.all %}
<li>{{ choice.choice_text }}</li>
{% endfor %}
</ul>